Created
February 14, 2019 08:36
-
-
Save andreasciamanna/4031fa35830af267d7986494cd3d210e to your computer and use it in GitHub Desktop.
Simple sorting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function sort_modules_by_position_only_A( $a, $b ) { | |
return (int) $a->position - (int) $b->position; | |
} | |
function sort_modules_by_position_only_B( $a, $b ) { | |
return ( (int) $a->position < (int) $b->position ) ? -1 : 1; | |
} | |
$data = array( | |
(object) array( 'name' => 'Test A', 'position' => 5 ), | |
(object) array( 'name' => 'Test B', 'position' => 4 ), | |
(object) array( 'name' => 'Test C', 'position' => 3 ), | |
(object) array( 'name' => 'Test D', 'position' => 2 ), | |
(object) array( 'name' => 'Test E', 'position' => 1 ), | |
); | |
uasort( $data, 'sort_modules_by_position_only_A' ); | |
var_export( $data ); | |
uasort( $data, 'sort_modules_by_position_only_B' ); | |
var_export( $data ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Andrea, I wanted to avoid the function to return a
0
. This happens when 2 blocks have the same position, but with 2 different parents.The sorting functions in PHP are not always stable, but it seems that it's slightly better when we return only
-1
or1
(maybe just an impression). Under the hood, the sorting algorithm is different depending on the size of the array.With both sorting function, you will see that the "position" order is respected, but we loose the original order when 2 elements have the same position.
This does not affect my logic because we have a second pass to re-order the parents and children.