-1

How can i sort my multidimensional array based on inner array value descending?

My array is:

array [
  0 => array [
    "name_TH" => "test"
    "currnetMonth" => 200.0
  ]
  1 => array [
    "name_TH" => "test2"
    "currnetMonth" => 3000.0
  ]
  2 => array [
    "name_TH" => "test3"
    "currnetMonth" => 1455.0
  ]
]

I try to do something like but still not sure how it's work with dimensional array

usort($data, function ($a, $b) {
  return dd($b);
});
Mohammad
  • 19,228
  • 14
  • 49
  • 73
TryHardz
  • 149
  • 2
  • 10
  • Check documentation for usort(): http://php.net/manual/en/function.usort.php You have to provide valid comparing function for usort function. Check the example there. Have no idea what dd() function is?!!? – MilanG Sep 18 '18 at 09:34

1 Answers1

1

The $a and $b in usort() is first level index of array that is also array. You should get currnetMonth index of $a or $b in function

usort($arr, function ($a, $b) {
    if ($b["currnetMonth"] == $a["currnetMonth"]) return 0;
    return $b["currnetMonth"] < $a["currnetMonth"] ? -1 : 1;
});

Or in write condition in one line

usort($arr, function ($a, $b) {
    return ($b["currnetMonth"] == $a["currnetMonth"]) ? 0 : ($b["currnetMonth"] < $a["currnetMonth"]) ? -1 : 1;
});

Check result in demo

Mohammad
  • 19,228
  • 14
  • 49
  • 73