PHP sorting a multidimensional array by key and non-zero values -



PHP sorting a multidimensional array by key and non-zero values -

[a, 1, 3, 9, 0, 13] [b, 5, 6, 0, 0, 11] [j, 0, 6, 2, 1, 9] [c, 1, 0, 8, 5, 14] [d, 0, 0, 0, 17, 17] [e, 0, 5, 0, 0, 5] [h, 0, 0, 3, 3, 6]

the array needs sorted on

ascending order of number of zeroes. ascending order of lastly element value.

so above array after sorting should like,

[j, 0, 6, 2, 1, 9] [a, 1, 3, 9, 0, 13] [c, 1, 0, 8, 5, 14] [h, 0, 0, 3, 3, 6] [b, 5, 6, 0, 0, 11] [d, 0, 5, 0, 0, 5] [d, 0, 0, 0, 17, 17]

i sorting multidimensional array against lastly value via code

function multiarraysorter($arr, $index) { $b = array(); $c = array(); foreach ($arr $key => $value) { $b[$key] = $value[$index]; } asort($b); foreach ($b $key => $value) { $c[] = $arr[$key]; } homecoming $c; }

any ideas how accomplish first sort based on number of zeroes of values?

you can utilize usort tasks this:

$arr=[['a', 1, 3, 9, 0, 13],['b', 5, 6, 0, 0, 11],['j', 0, 6, 2, 1, 9],['c', 1, 0, 8, 5, 14],['d', 0, 0, 0, 17, 17],['e', 0, 5, 0, 0, 5],['h', 0, 0, 3, 3, 6]]; usort($arr,function($a,$b){ $infoa=array_count_values($a); $infob=array_count_values($b); if(empty($infoa[0])) $infoa[0]=0; if(empty($infob[0])) $infob[0]=0; if($infoa[0]==$infob[0]) { homecoming end($a)-end($b); } else { homecoming $infoa[0]-$infob[0]; } }); print_r($arr);

3v4l.org demo

the generated output is:

array ( [0] => array ( [0] => j [1] => 0 [2] => 6 [3] => 2 [4] => 1 [5] => 9 ) [1] => array ( [0] => [1] => 1 [2] => 3 [3] => 9 [4] => 0 [5] => 13 ) [2] => array ( [0] => c [1] => 1 [2] => 0 [3] => 8 [4] => 5 [5] => 14 ) [3] => array ( [0] => h [1] => 0 [2] => 0 [3] => 3 [4] => 3 [5] => 6 ) [4] => array ( [0] => b [1] => 5 [2] => 6 [3] => 0 [4] => 0 [5] => 11 ) [5] => array ( [0] => e [1] => 0 [2] => 5 [3] => 0 [4] => 0 [5] => 5 ) [6] => array ( [0] => d [1] => 0 [2] => 0 [3] => 0 [4] => 17 [5] => 17 ) )

php arrays sorting multidimensional-array

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -