note 93473 modified in function.sort by thiago

From: Date: Fri, 11 Sep 2009 13:31:28 +0000
Subject: note 93473 modified in function.sort by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160454@lists.php.net to get a copy of this message
Here is a function to sort an array by the key of his sub-array with keep key in top level. <?php function sksort(&$array, $subkey="id", $sort_descending=false, $keep_keys_in_sub = false) { $temp_array = $array; foreach ($temp_array as $key => &$value) { $sort = array(); foreach ($value as $index => $val) { $sort[$index] = $val[$subkey]; } asort($sort); $keys = array_keys($sort); $newValue = array(); foreach ($keys as $index) { if($keep_keys_in_sub) $newValue[$index] = $value[$index]; else $newValue[] = $value[$index]; } if($sort_descending) $value = array_reverse($newValue, $keep_keys_in_sub); else $value = $newValue; } $array = $temp_array; } ?> --was-- Here is a function to sort an array by the key of his sub-array with keep key in top level. function sksort(&$array, $subkey="id", $sort_descending=false, $keep_keys_in_sub = false) { $temp_array = $array; foreach ($temp_array as $key => &$value) { $sort = array(); foreach ($value as $index => $val) { $sort[$index] = $val[$subkey]; } asort($sort); $keys = array_keys($sort); $newValue = array(); foreach ($keys as $index) { if($keep_keys_in_sub) $newValue[$index] = $value[$index]; else $newValue[] = $value[$index]; } if($sort_descending) $value = array_reverse($newValue, $keep_keys_in_sub); else $value = $newValue; } $array = $temp_array; } http://php.net/manual/en/function.sort.php

« previous php.notes (#160454) next »