php - Sorting Multidimensional Array by Specific Key -
edit: might come across post similar problem, solved taking konforce's supplied answer , tweaking around bit custom sorting function:
function cmp($a, $b) { if ($a[5] == $b[5]) { return ($a[3] < $b[3]) ? -1 :1; } return ($a[5] > $b[5]) ? -1 : 1; }
notice $a[5] == $b[5]
not return zero. changed check has losses , sort in asc order. i'm sure can keep going , add if-statement in there in-case have same losses.
lastly, usort($array, "cmp");
, finito!!!
original post
my apologies coming yet md array sorting question i'm not getting it. i've searched aplenty solution , although many sites have provided seemed logical answer still have not been able figure out.
my problem since i'm still learning been rather difficult me grasp concept of using usort custom comparing function. atleast, thats have seen when others have tried sort md arrays.
i'm working on small project sharpen on php skills. basic tournament standings script holds team's information within array. sort array points($array[x][x][5]).
so array looks this:
array ( [0] => array ( [0] => array ( [0] => cooller [1] => 6 [2] => 6 [3] => 0 [4] => 0 [5] => 18 ) ) [1] => array ( [0] => array ( [0] => strenx [1] => 9 [2] => 5 [3] => 1 [4] => 3 [5] => 18 ) ) [2] => array ( [0] => array ( [0] => rapha [1] => 10 [2] => 8 [3] => 1 [4] => 1 [5] => 25 ) ) [3] => array ( [0] => array ( [0] => ronald reagan [1] => 5 [2] => 4 [3] => 0 [4] => 1 [5] => 13 ) ) )
i sort points(cell #5), after sorting:
array ( [0] => array ( [0] => array ( [0] => rapha [1] => 10 [2] => 8 [3] => 1 [4] => 1 [5] => 25 ) ) [1] => array ( [0] => array ( [0] => cooller [1] => 6 [2] => 6 [3] => 0 [4] => 0 [5] => 18 ) ) [2] => array ( [0] => array ( [0] => strenx [1] => 9 [2] => 5 [3] => 1 [4] => 3 [5] => 18 ) ) [3] => array ( [0] => array ( [0] => ronald reagan [1] => 5 [2] => 4 [3] => 0 [4] => 1 [5] => 13 ) ) )
the player 25 points @ top, followed 18, 18, , lastly 13. sorry earlier post, having difficulty wording question correctly. in advanced!
i think want this:
usort($standings, function($a, $b) { return $b[0][5] - $a[0][5]; });
or prior php 5.3:
function cmp($a, $b) { return $b[0][5] - $a[0][5]; } usort($standings, 'cmp');
when using usort
, $a
, $b
parameters 1 "layer" supplied array. in case, example of $a
or $b
be:
[0] => array ( [0] => cooller [1] => 6 [2] => 6 [3] => 0 [4] => 0 [5] => 18 )
i'm not sure why have containing array there, can see, want sort based on [0][5]
position.
Comments
Post a Comment