Skip to content

Instantly share code, notes, and snippets.

@Pegasuz
Forked from tufanbarisyildirim/sort_array_multidim.php
Created December 15, 2016 13:33
Show Gist options
  • Save Pegasuz/41365e3871646a2dfbf666e61bc9fba1 to your computer and use it in GitHub Desktop.
Save Pegasuz/41365e3871646a2dfbf666e61bc9fba1 to your computer and use it in GitHub Desktop.
sort a multidimensional array by sql like order by clause
<?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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment