note 98765 deleted from function.array-multisort by danbrown

From: Date: Tue, 06 Jul 2010 13:01:40 +0000
Subject: note 98765 deleted from function.array-multisort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-170732@lists.php.net to get a copy of this message
Note Submitter: Christian Kaps ---- @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; } ?>

« previous php.notes (#170732) next »