php - Sort multidimensional array by keys - fails on duplicates -
this question has answer here:
i have function sortby()
use sort multidimensional arrays particular key. here sample array:
array ( [0] => array ( [id] => 4 [type] => 1 [game] => 1 [platform] => 0 [totalpot] => 7550 ) [1] => array ( [id] => 5 [type] => 0 [game] => 2 [platform] => 0 [totalpot] => 7500 ) )
here function
function sortby($arr, $field='id', $order=1) { $a = array(); if ( !is_array($arr) ) return false; foreach($arr $subarr) { $a[$subarr[$field]] = $subarr; } if ( $order == 1 ) sort($a); else rsort($a); return $a; }
in case, calling sortby($array, 'totalpot');
work fine, because 2 values totalpot
different. however, if run example , set both totalpot
fields $7500, overwrites first occurrence latter.
what best way make function allow 2 items same value still keep them in relevant order? thought adding character, a
or 1
end, seems sloppy , not predictable, better course of action appreciated.
you can simplify code , use usort()
, e.g.
function sortarraybyfield(array &$arr, $field = "id", $asc = true) { usort($arr, function($a, $b)use($field, $asc){ if($a[$field] == $b[$field]) return 0; return $a[$field] > $b[$field] ? $asc : !$asc; }); }
then call this:
sortarraybyfield($array, "totalpot", true); print_r($array);
Comments
Post a Comment