note 98465 added to function.ksort

From: Date: Thu, 17 Jun 2010 13:47:22 +0000
Subject: note 98465 added to function.ksort
Groups: php.notes 
Request: Send a blank email to php-notes+get-170201@lists.php.net to get a copy of this message
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first: $people = array( array("name"=>"Bob","age"=>8,"colour"=>"red"), array("name"=>"Greg","age"=>12,"colour"=>"blue"), array("name"=>"Andy","age"=>5,"colour"=>"purple")); var_dump($people); $sortArray = array(); foreach($people as $person){ foreach($person as $key=>$value){ if(!isset($sortArray[$key])){ $sortArray[$key] = array(); } $sortArray[$key][] = $value; } } $orderby = "name"; //change this to whatever key you want from the array array_multisort($sortArray[$orderby],SORT_DESC,$people); var_dump($people); Output from first var_dump: [0]=> array(3) { ["name"]=> string(3) "Bob" ["age"]=> int(8) ["colour"]=> string(3) "red" } [1]=> array(3) { ["name"]=> string(4) "Greg" ["age"]=> int(12) ["colour"]=> string(4) "blue" } [2]=> array(3) { ["name"]=> string(4) "Andy" ["age"]=> int(5) ["colour"]=> string(6) "purple" } } Output from 2nd var_dump: array(3) { [0]=> array(3) { ["name"]=> string(4) "Greg" ["age"]=> int(12) ["colour"]=> string(4) "blue" } [1]=> array(3) { ["name"]=> string(3) "Bob" ["age"]=> int(8) ["colour"]=> string(3) "red" } [2]=> array(3) { ["name"]=> string(4) "Andy" ["age"]=> int(5) ["colour"]=> string(6) "purple" } There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add. ---- Server IP: 92.48.74.199 Probable Submitter: 89.16.226.107 ---- Manual Page -- http://www.php.net/manual/en/function.ksort.php Edit -- https://master.php.net/note/edit/98465 Del: integrated -- https://master.php.net/note/delete/98465/integrated Del: useless -- https://master.php.net/note/delete/98465/useless Del: bad code -- https://master.php.net/note/delete/98465/bad+code Del: spam -- https://master.php.net/note/delete/98465/spam Del: non-english -- https://master.php.net/note/delete/98465/non-english Del: in docs -- https://master.php.net/note/delete/98465/in+docs Del: other reasons-- https://master.php.net/note/delete/98465 Reject -- https://master.php.net/note/reject/98465 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#170201) next »