0

I would like to sort this array by a value that is in a sub table. I tried with the method Usort (), but impossible to sort.

    foreach ($res as $r) {
        usort($r, function($a1, $a2) {
            $v1 = $a1['WeekNumDay'];
            $v2 = $a2['WeekNumDay'];
            return $v1 - $v2; // $v2 - $v1 to reverse direction
        });
    }

In my array I would like to sort by key ['WeekNumDay'].

Array
(
    [R422] => Array
        (

            [0] => Array
                (
                    [WeekNumDay] => 19321
                    [Day1DeliveryTime] => 52932000
                )

            [1] => Array
                (
                    [WeekNumDay] => 18331
                    [Day1DeliveryTime] => 42770000
                )

            [2] => Array
                (
                    [WeekNumDay] => 19305
                    [Day1DeliveryTime] => null
                )
        )

)

Can you help me ?

1
  • 4
    it seems to work. but you don't save results, use reference in foreach foreach ($res as & $r) { Commented Aug 7, 2019 at 13:43

2 Answers 2

1

Should work if you just change these lines:

foreach ($res as $r) {
    usort($r, function($a1, $a2) {
        // ...
    });
}

to the following:

foreach ($res as $k => $r) {

    usort($r, function($a1, $a2) {
        // ...
    });

    $res[$k] = $r; // Edit the original array.

}

The reason it should work is because usort accepts the array as a reference, once you have sorted $r into the correct order you will then need to alter the original array, hence:

$res[$k] = $r;
Sign up to request clarification or add additional context in comments.

1 Comment

"$res[$k] and $r essentially are the same thing, but one is the array and one is an element of the array." Heuh? No. By the way usort first argument is passed by reference.
1
foreach ($arr as $k => $v) {
    usort($v, function ($a1, $a2) {
        return $a1['WeekNumDay'] <=> $a2['WeekNumDay']; //spaceship operator only php 7+
    });
    $arr[$k] = $v; //important to return the sorted array to the original container array
}

Note: usort first argument is passed by reference, so passing $arr[$k] would work as well since php would figure where the container of $v.

Read more about spaceship operator.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.