Skip to content

Instantly share code, notes, and snippets.

@Loupax
Created July 4, 2012 17:47
Show Gist options
  • Save Loupax/3048566 to your computer and use it in GitHub Desktop.
Save Loupax/3048566 to your computer and use it in GitHub Desktop.
Group sorting Final
/**
* Sorts a multidimentional array in groups. The sorting sequence is provided by using an array
* that contains the keys that should be grouped
*
* @param array $array
* @param array $order
*/
function group_sort(&$array, $order)
{
if(!$array)
{
return FALSE;
}
$all_keys = array();
foreach(reset($array) as $key=>$row)
{
$all_keys[] = $key;
}
$all_keys = array_unique(array_merge($order, $all_keys));
$all_keys = array_merge($all_keys, array());
$new = array();
foreach ($array as $row){
foreach ($all_keys as $ord){
$new[$ord][] = $row[$ord];
}
}
$str = '';
for ($i=0; $i<count($all_keys); $i++)
{
$str .= '$new[$all_keys['.$i.']],';
}
//Remove the last coma
$str = substr_replace($str ,"",-1);
eval('array_multisort('.$str.');');
$out = array();
foreach(reset($new) as $index=>$data)
{
$temp = array();
foreach($all_keys as $key)
{
$temp[$key] = $new[$key][$index];
}
$out[] = $temp;
}
$array = $out;
return TRUE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment