Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Sort multi-array by deeper than level-1 dimension values with given field order [duplicate]

My array:

$MY_ARRAY = 
Array
(
    [0] => Array
        (
            [0] => 2861
            [1] => Array
                (
                    [start_month] => 6
                    [start_year] => 1970
                    [end_month] => 12
                    [end_year] => 1990
                    [experience_info] => "Practically a random string"
                )

        )

)

And I would like to sort $MY_ARRAY direct children by their inner contents, ideally in an order of start_year, start_month, end_year, end_month. I guess I could use the array_multisort() somehow, but I don't know how. Does anyone know how to deal with this?

Thanks.

EDIT: As it showed up, the solution was nice and simple, what I didnt know is that during the comparsion in callback-compare-function you can go to the deeper structure - so if your deeper than lvl-1 indexes remains always the same (my case) that is how to do it :)

like image 598
jave.web Avatar asked Nov 02 '22 05:11

jave.web


1 Answers

For this purpose you can use uasort function:

function compare_callback($arr1, $arr2) {
    $start_year1 = $arr1[1]['start_year'];
    $start_year2 = $arr2[1]['start_year'];

    $start_month1 = $arr1[1]['start_month'];
    $start_month2 = $arr2[1]['start_month'];

    $end_year1 = $arr1[1]['end_year'];
    $end_year2 = $arr2[1]['end_year'];

    $end_month1 = $arr1[1]['end_month'];
    $end_month2 = $arr2[1]['end_month'];

    return ($start_year1 === $start_year2)
        ? (($start_month1 === $start_month2)
            ? (($end_year1 === $end_year2)
                ? (($end_month1 === $end_month2)
                    ? 0
                    : (($end_month1 < $end_month2) ? -1 : 1))
                : (($end_year1 < $end_year2) ? -1 : 1))
            : ($start_month1 < $start_month2) ? -1 : 1)
        : (($start_year1 < $start_year2) ? -1 : 1);
}

uasort($array, 'compare_callback');
like image 139
Alexander Yancharuk Avatar answered Nov 09 '22 13:11

Alexander Yancharuk