public
Last active

sort a multidimensional array by sql like order by clause

  • Download Gist
sort_array_multidim.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
<?php
/**
* @name Mutlidimensional Array Sorter.
* @author Tufan Barış YILDIRIM
* @link http://www.tufanbarisyildirim.com
* @github http://github.com/tufanbarisyildirim
*
* This function can be used for sorting a multidimensional array by sql like order by clause
*
* @param mixed $array
* @param mixed $order_by
* @return array
*/
function sort_array_multidim(array $array, $order_by)
{
//TODO -c flexibility -o tufanbarisyildirim : this error can be deleted if you want to sort as sql like "NULL LAST/FIRST" behavior.
if(!is_array($array[0]))
throw new Exception('$array must be a multidimensional array!',E_USER_ERROR);
 
$columns = explode(',',$order_by);
foreach ($columns as $col_dir)
{
if(preg_match('/(.*)([\s]+)(ASC|DESC)/is',$col_dir,$matches))
{
if(!array_key_exists(trim($matches[1]),$array[0]))
trigger_error('Unknown Column <b>' . trim($matches[1]) . '</b>',E_USER_NOTICE);
else
{
if(isset($sorts[trim($matches[1])]))
trigger_error('Redundand specified column name : <b>' . trim($matches[1] . '</b>'));
 
$sorts[trim($matches[1])] = 'SORT_'.strtoupper(trim($matches[3]));
}
}
else
{
throw new Exception("Incorrect syntax near : '{$col_dir}'",E_USER_ERROR);
}
}
 
//TODO -c optimization -o tufanbarisyildirim : use array_* functions.
$colarr = array();
foreach ($sorts as $col => $order)
{
$colarr[$col] = array();
foreach ($array as $k => $row)
{
$colarr[$col]['_'.$k] = strtolower($row[$col]);
}
}
$multi_params = array();
foreach ($sorts as $col => $order)
{
$multi_params[] = '$colarr[\'' . $col .'\']';
$multi_params[] = $order;
}
 
$rum_params = implode(',',$multi_params);
eval("array_multisort({$rum_params});");
 
 
$sorted_array = array();
foreach ($colarr as $col => $arr)
{
foreach ($arr as $k => $v)
{
$k = substr($k,1);
if (!isset($sorted_array[$k]))
$sorted_array[$k] = $array[$k];
$sorted_array[$k][$col] = $array[$k][$col];
}
}
 
return array_values($sorted_array);
 
}
 
 
#Example using.
 
$array = array(
array('name' => 'Tufan Barış','surname' => 'YILDIRIM'),
array('name' => 'Tufan Barış','surname' => 'xYILDIRIM'),
array('name' => 'Tufan Barış','surname' => 'aYILDIRIM'),
array('name' => 'Tufan Barış','surname' => 'bYILDIRIM'),
array('name' => 'Ahmet','surname' => 'Altay'),
array('name' => 'Zero','surname' => 'One'),
);
 
$order_by_name = sort_array_multidim($array,'name DESC,surname ASC,xname DESC,name ASC');
 
#output.
echo '<pre>';
var_dump($order_by_name);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.