Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Last active January 4, 2016 13:38
Show Gist options
  • Save martynchamberlin/8628758 to your computer and use it in GitHub Desktop.
Save martynchamberlin/8628758 to your computer and use it in GitHub Desktop.
Sort a PHP array based on a subarray.
<?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