Sort a two-dimensional array

I am new to PHP. I have a PHP array that is two dimensional. The "internal" array has the value that I want to sort.

For instance:

$myarray[1]['mycount']=12
$myarray[2]['mycount']=13
$myarray[3]['mycount']=9

I want to sort the "inner" array in descending order.

Thus, the results for the next will be 13, 12, 9

foreach ($myarray as $myarr){
  print $myarr['mycount']
}

early.

+3
source share
2 answers

You can use usort();to sort by user comparison.

// Our own custom comparison function
function fixem($a, $b){
  if ($a["mycount"] == $b["mycount"]) { return 0; }
  return ($a["mycount"] < $b["mycount"]) ? -1 : 1;
}

// Our Data
$myarray[0]['mycount']=12
$myarray[1]['mycount']=13
$myarray[2]['mycount']=9

// Our Call to Sort the Data
usort($myArray, "fixem");

// Show new order
print "<pre>";
print_r($myArray);
print "</pre>";
+7
source
+4
source

Source: https://habr.com/ru/post/1726717/


All Articles