Skip to content

Instantly share code, notes, and snippets.

@andreasciamanna
Created February 14, 2019 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreasciamanna/4031fa35830af267d7986494cd3d210e to your computer and use it in GitHub Desktop.
Save andreasciamanna/4031fa35830af267d7986494cd3d210e to your computer and use it in GitHub Desktop.
Simple sorting
<?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 );
@strategio
Copy link

@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 or 1 (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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment