Angel Valdez Angel Valdez -4 years ago 99
PHP Question

order by key array multidimensional

I have this multidimensional array, and i want to order each array by 'fecha'(i mean 2017-02-20, then 2017-02-21, then 2017-02-22 and finally 2017-02-23). I have read a lot of answers, but they only work with bidimensional arrays. I have tried with unsort and array_multisort, even with ksort bue i couldnĀ“t obtain the desire result.

Array
(
[0.10] => Array
(
[0] => Array
(
[fecha] => 2017-02-21
[tarifa] => 743.80
[percent] => 0.10
)

[1] => Array
(
[fecha] => 2017-02-22
[tarifa] => 743.80
[percent] => 0.10
)

[2] => Array
(
[fecha] => 2017-02-20
[tarifa] => 743.80
[percent] => 0
)

[3] => Array
(
[fecha] => 2017-02-23
[tarifa] => 743.80
[percent] => 0
)

)

[0.15] => Array
(
[0] => Array
(
[fecha] => 2017-02-21
[tarifa] => 743.80
[percent] => 0.15
)

[1] => Array
(
[fecha] => 2017-02-22
[tarifa] => 743.80
[percent] => 0.15
)

[2] => Array
(
[fecha] => 2017-02-20
[tarifa] => 743.80
[percent] => 0
)

[3] => Array
(
[fecha] => 2017-02-23
[tarifa] => 743.80
[percent] => 0
)

)

)

Answer Source

you can use usort with strtotime to order by date.

ASC Order by date (fecha):

foreach ($yourArray as $key => $subarray) {
    usort($subarray, function($a, $b) {
            return strtotime($a['fecha']) - strtotime($b['fecha']);
        });
    $yourArray[$key] = $subarray;
 }

print_r($yourArray);

DESC order by date (fecha):

foreach ($yourArray as $key => $subarray) {
    usort($subarray, function($a, $b) {
            return strtotime($b['fecha']) - strtotime($a['fecha']);
        });
    $yourArray[$key] = $subarray;
 }

print_r($yourArray);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download