Skip to content

Instantly share code, notes, and snippets.

@geminorum
Forked from alkavan/sksort.php
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geminorum/7d91dc0eca7740021e91 to your computer and use it in GitHub Desktop.
Save geminorum/7d91dc0eca7740021e91 to your computer and use it in GitHub Desktop.
<?php
/**
* A function to sort data array element by one or two sub keys, both directions
*/
function sksort(&$array, $subkey = "id", $subkey2 = null ,$sort_ascending=false)
{
if (count($array))
$temp_array[key($array)] = array_shift($array);
foreach($array as $key => $val){
$offset = 0;
$found = false;
foreach($temp_array as $tmp_key => $tmp_val)
{
if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
{
$temp_array = array_merge(
(array)array_slice($temp_array,0,$offset), array($key => $val),
array_slice($temp_array,$offset));
$found = true;
}
elseif(!$found
and $subkey2 and strtolower($val[$subkey]) == strtolower($tmp_val[$subkey])
and strtolower($val[$subkey2]) > strtolower($tmp_val[$subkey2]))
{
$temp_array = array_merge(
(array)array_slice($temp_array,0,$offset),
array($key => $val), array_slice($temp_array,$offset));
$found = true;
}
$offset++;
}
if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
}
if ($sort_ascending) $array = array_reverse($temp_array);
else $array = $temp_array;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment