note 117725 added to function.array-multisort

From: Date: Wed, 29 Jul 2015 09:09:50 +0000
Subject: note 117725 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-203211@lists.php.net to get a copy of this message
Many users have contributed nifty wrapper functions for generalizing array_multisort. However, some of us may just want a simple example that illustrates how to sort an arbitrary multi-dimensional array, such as a database result set, on a named field. Consider an array of voice recordings (Clip objects) that are stored on a file system, and referenced via a database table: $fetchClipQuery = "SELECT * from voiceclips"; if ( !$result = $this->db->query($fetchClipQuery) ) { $errormessage = $this->db->errno; $errormessage .= $this->db->error; } else { while($row = $result->fetch_assoc()){ $clip = new Clip(); $clip->populate($row['clipURL']); $clips[] = array("speaker"=>$row['speaker'],"duration"=>$row['duration'],"clip"=>$clip); } //we now have an array called clips[] that looks like this: array("speaker"=>"Obama","duration"=>"22:00","clip"=>...<some arbitrary object>...); //suppose we want to sort the array by speaker $sortkeyname = "speaker"; //do the sort $sortkeyarray = array(); foreach ($clips as $key => $row){ $sortkeyarray[$key] = $row[$sortkeyname]; } array_multisort($sortkeyarray, SORT_DESC, $clips); //suppose we want to sort the array by duration $sortkeyname = "duration"; //do the sort $sortkeyarray = array(); foreach ($clips as $key => $row){ $sortkeyarray[$key] = $row[$sortkeyname]; } array_multisort($sortkeyarray, SORT_DESC, $clips); ...etc. ---- Server IP: 72.52.91.14 Probable Submitter: 49.207.181.92 ---- Manual Page -- http://php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/117725 Del: integrated -- https://master.php.net/note/delete/117725/integrated Del: useless -- https://master.php.net/note/delete/117725/useless Del: bad code -- https://master.php.net/note/delete/117725/bad+code Del: spam -- https://master.php.net/note/delete/117725/spam Del: non-english -- https://master.php.net/note/delete/117725/non-english Del: in docs -- https://master.php.net/note/delete/117725/in+docs Del: other reasons-- https://master.php.net/note/delete/117725 Reject -- https://master.php.net/note/reject/117725 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203211) next »