Last active
January 4, 2016 13:38
-
-
Save martynchamberlin/8628758 to your computer and use it in GitHub Desktop.
Sort a PHP array based on a subarray.
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 orderBySubArray( &$array, $new_key = 'order', $order = 'ascending', $start_at = 1 ) | |
{ | |
$output = array(); | |
$count = count( $array ); | |
$i = ( $order == 'ascending' ) ? $start_at : $count; | |
for ( $j = 1; $j <= $count; $j++ ) | |
{ | |
foreach ( $array as $key => &$item ) | |
{ | |
if ( $item[ $new_key ] == $i ) | |
{ | |
array_push( $output, $item ); | |
unset( $array[$key] ); // reduces items to be inspected by 2X on average | |
$i = ( $order == 'ascending' ) ? $i + 1 : $i - 1; | |
break; | |
} | |
} | |
} | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment