note 89552 added to function.ksort

From: Date: Fri, 13 Mar 2009 10:02:43 +0000
Subject: note 89552 added to function.ksort
Groups: php.notes 
Request: Send a blank email to php-notes+get-151821@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. <?php function sksort(&$array, $subkey="id", $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; } $offset++; } if(!$found) $temp_array = array_merge($temp_array, array($key => $val)); } if ($sort_ascending) $array = array_reverse($temp_array); else $array = $temp_array; } ?> Example <?php $info = array("peter" => array("age" => 21, "gender" => "male" ), "john" => array("age" => 19, "gender" => "male" ), "mary" => array("age" => 20, "gender" => "female" ) ); sksort($info, "age"); var_dump($info); sksort($info, "age", true); var_dump($ifno); ?> This will be the output of the example: /*DESCENDING SORT*/ array(3) { ["peter"]=> array(2) { ["age"]=> int(21) ["gender"]=> string(4) "male" } ["mary"]=> array(2) { ["age"]=> int(20) ["gender"]=> string(6) "female" } ["john"]=> array(2) { ["age"]=> int(19) ["gender"]=> string(4) "male" } } /*ASCENDING SORT*/ array(3) { ["john"]=> array(2) { ["age"]=> int(19) ["gender"]=> string(4) "male" } ["mary"]=> array(2) { ["age"]=> int(20) ["gender"]=> string(6) "female" } ["peter"]=> array(2) { ["age"]=> int(21) ["gender"]=> string(4) "male" } } ---- Server IP: 130.206.1.5 Probable Submitter: 212.163.4.98 ---- Manual Page -- http://www.php.net/manual/en/function.ksort.php Edit -- https://master.php.net/note/edit/89552 Del: integrated -- https://master.php.net/note/delete/89552/integrated Del: useless -- https://master.php.net/note/delete/89552/useless Del: bad code -- https://master.php.net/note/delete/89552/bad+code Del: spam -- https://master.php.net/note/delete/89552/spam Del: non-english -- https://master.php.net/note/delete/89552/non-english Del: in docs -- https://master.php.net/note/delete/89552/in+docs Del: other reasons-- https://master.php.net/note/delete/89552 Reject -- https://master.php.net/note/reject/89552 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#151821) next »