kunal
kunal

Reputation: 4248

Sort array in ASC order depending on two key values?

I have one array that is stored in one variable. The array is following:

Array
(
[0] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-11
    )

[1] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-09
    )

[2] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-10
    )
[3] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-11
    )

[4] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-10
    )
)

I have done with sorting of array in ascending with employee_name that is running very fine with this code:

$attendances = "above array";
uasort($attendances, function($a, $b) {
     return strcmp($a["employee_name"], $b["employee_name"]);
 }); // this code is sorting in ascending order with employee_name.

Now what i want is that every employee_name should be ascending order and each employee_name today_date should also be in ascending order. My expected output is like that:

Array
(
[0] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-09
    )

[1] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-10
    )

[2] => Array
    (
        [employee_name] => Amit
        [today_date] => 2018-01-11
    )
[3] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-10
    )

[4] => Array
    (
        [employee_name] => GURVINDER
        [today_date] => 2018-01-11
    )
)

Please help me how to resolve this problem. I will not go with SQL query for some reasons. Thanks in advance.

Upvotes: 4

Views: 128

Answers (1)

Hetal Chauhan
Hetal Chauhan

Reputation: 807

This works fine based on your output requirement. Try this:

array_multisort(array_column($attendances, 'employee_name'),  SORT_ASC,
            array_column($attendances, 'today_date'), SORT_ASC,
            $attendances);
echo "<pre>";
print_r($attendances);

Output:-https://eval.in/935967

Upvotes: 4

Related Questions