PHP - Sorting of a key on a multi-dimensional array


/ Published in: PHP
Save to your folder(s)

A nice way to do sorting of a key on a multi-dimensional array - DavidG


Copy this code and paste it in your HTML
  1. $people = array(
  2. array("name"=>"Bob","age"=>8,"colour"=>"red"),
  3. array("name"=>"Greg","age"=>12,"colour"=>"blue"),
  4. array("name"=>"Andy","age"=>5,"colour"=>"purple")
  5. );
  6.  
  7. $arrSortArray = array();
  8.  
  9. foreach($people as $person) {
  10. foreach($person as $key=>$value){
  11. if(!isset($arrSortArray[$key])){
  12. $arrSortArray[$key] = array();
  13. }
  14. $arrSortArray[$key][] = $value;
  15. }
  16. }
  17.  
  18. $orderby = "name"; //change this to whatever key you want from the array
  19.  
  20. array_multisort($arrSortArray[$orderby],SORT_DESC,$people);

URL: http://goo.gl/tyM6x

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.