PHP: Sorting multiple arrays deeper than level 1 dimension values ​​with a given field order

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 the $MY_ARRAYdirect children by their internal content, ideally in the order start_year, start_month, end_year, end_month . I think I could use it somehow array_multisort(), but I don’t know how to do it. Does anyone know how to deal with this?

Thanks.

EDIT: As it turned out, the solution was nice and simple, which I did not know, is that during the comparison in the callback-compare function you can go to a deeper structure - so if yours is deeper than the lvl-1 indices, always remains the same (my case) how to do this :)

+4
3

uasort:

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');
+1

PHP usort . :

function cmp($a, $b)
{
    if ($a[1]['start_year'] == $b[1]['start_year'])
    {
        // You can further do tests for start_month, etc in here if start_years are equal
        return 0;
    }
    return ($a[1]['start_year'] > $b[1]['start_year']) ? 1 : -1;
}

usort($MY_ARRAY, "cmp");

start_year. , .

+1

Do something like the following:

$newArray = array();
foreach($MY_ARRAY as $value) {
    $newArray[] = $value[1];
}
multi_sort($newArray, $MY_ARRAY);
0
source

Source: https://habr.com/ru/post/1527256/


All Articles