note 98765 added to function.array-multisort

From: Date: Tue, 06 Jul 2010 10:04:42 +0000
Subject: note 98765 added to function.array-multisort
Groups: php.notes 
Request: Send a blank email to php-notes+get-170728@lists.php.net to get a copy of this message
@d_inkubus at yahoo dot com Your version doesn't work as expected. You create a reference always to the same variable, so your order reference has always the same value. You can test it if you write a print_r($params) before the call_user_func_array call. In your example the output is: <?php $array = array(); $array[] = array('id' => 1, 'value' => 1); $array[] = array('id' => 2, 'value' => 2); $array[] = array('id' => 3, 'value' => 3); array_msort($array, array('id' => SORT_ASC, 'value' => SORT_DESC)); ?> Array ( [0] => Array ( [_0] => 1 [_1] => 2 [_2] => 3 ) [1] => 3 [2] => Array ( [_0] => 1 [_1] => 2 [_2] => 3 ) [3] => 3 ) Key 1 and 3 have the same values but the expected result is: Array ( [0] => Array ( [_0] => 1 [_1] => 2 [_2] => 3 ) [1] => 4 [2] => Array ( [_0] => 1 [_1] => 2 [_2] => 3 ) [3] => 3 ) ?> The problem can be avoided if you use variable variables. <?php function array_msort($array, $cols) { $i = 0; $colarr = array(); $params = array(); foreach ($cols as $col => $order) { $colarr[$col] = array(); foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); } ${$col . $order . $i} = $order; $params[] = &$colarr[$col]; $params[] = &${$col . $order . $i}; $i++; } call_user_func_array('array_multisort', $params); $ret = array(); $keys = array(); $first = true; foreach ($colarr as $col => $arr) { $i = 0; foreach ($arr as $k => $v) { if ($first) $keys[$k] = substr($k,1); $k = $keys[$k]; if (!isset($ret[$i])) $ret[$i] = $array[$k]; $ret[$i][$col] = $array[$k][$col]; $i++; } $first = false; } return $ret; } ?> ---- Server IP: 212.124.37.9 Probable Submitter: 80.152.160.161 ---- Manual Page -- http://www.php.net/manual/en/function.array-multisort.php Edit -- https://master.php.net/note/edit/98765 Del: integrated -- https://master.php.net/note/delete/98765/integrated Del: useless -- https://master.php.net/note/delete/98765/useless Del: bad code -- https://master.php.net/note/delete/98765/bad+code Del: spam -- https://master.php.net/note/delete/98765/spam Del: non-english -- https://master.php.net/note/delete/98765/non-english Del: in docs -- https://master.php.net/note/delete/98765/in+docs Del: other reasons-- https://master.php.net/note/delete/98765 Reject -- https://master.php.net/note/reject/98765 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#170728) next »