note 109943 added to function.array-multisort

From: Date: Tue, 04 Sep 2012 14:56:48 +0000
Subject: note 109943 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-190490@lists.php.net to get a copy of this message
multisort an Array of Objects: example object [$object with array of objects]: (class: test) ---------------------------------- test Object ( [Artikel] => Array ( [0] => test Object ( [id] => 1 [title] => CCCC ) [1] => test Object ( [id] => 2 [title] => AAAA ) [2] => test Object ( [id] => 3 [title] => DDDD ) [3] => test Object ( [id] => 4 [title] => BBBB ) ) ) ---------------------------------- Simple PHP function: sort_arr_of_obj() <?php // -------------------------------------- /* * -------- function arguments -------- * $array ........ array of objects * $sortby ....... the object-key to sort by * $direction ... 'asc' = ascending * -------- */ function sort_arr_of_obj($array, $sortby, $direction='asc') { $sortedArr = array(); $tmp_Array = array(); foreach($array as $k => $v) { $tmp_Array[] = strtolower($v->$sortby); } if($direction=='asc'){ asort($tmp_Array); }else{ arsort($tmp_Array); } foreach($tmp_Array as $k=>$tmp){ $sortedArr[] = $array[$k]; } return $sortedArr; } // -------------------------------------- ?> example call: ---------------------------------- <?php $sorted->Artikel = sort_arr_of_obj($object->Artikel,'title','asc'); ?> example result: $sorted (class: test) ---------------------------------- test Object ( [Artikel] => Array ( [0] => test Object ( [id] => 2 [title] => AAAA ) [1] => test Object ( [id] => 4 [title] => BBBB ) [2] => test Object ( [id] => 1 [title] => CCCC ) [3] => test Object ( [id] => 3 [title] => DDDD ) ) ) ------------------------- :) ---- Server IP: 69.147.83.197 Probable Submitter: 84.168.215.111 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/109943 Del: integrated -- https://master.php.net/note/delete/109943/integrated Del: useless -- https://master.php.net/note/delete/109943/useless Del: bad code -- https://master.php.net/note/delete/109943/bad+code Del: spam -- https://master.php.net/note/delete/109943/spam Del: non-english -- https://master.php.net/note/delete/109943/non-english Del: in docs -- https://master.php.net/note/delete/109943/in+docs Del: other reasons-- https://master.php.net/note/delete/109943 Reject -- https://master.php.net/note/reject/109943 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#190490) next »