Sorting multiple multidimensional arrays with array elements

Let's say I started here:

$arr[0] = array('a' => 'a', 'int' => 10);
$arr[1] = array('a' => 'foo', 'int' => 5);
$arr[2] = array('a' => 'bar', 'int' => 12);

And I want to get here:

$arr[0] = array('a' => 'foo', 'int' => 5);
$arr[1] = array('a' => 'a', 'int' => 10);
$arr[2] = array('a' => 'bar', 'int' => 12);

How can I sort the elements in an array using the elements of these elements?

Multidimensional arrays always feel a little more than my brain can handle (-_-) (until I figure them out and they seem very light)

+3
source share
2 answers

Do you want to order them by the key value "int"?

Use uasort with callback function:

function compare_by_int_key($a, $b) {
    if ($a['int'] == $b['int']) {
        return 0;
    }
    return ($a['int'] < $b['int']) ? -1 : 1;
}
uasort($arr, "compare_by_int_key");
+4
source

, , cuz. , $arr [1].

:

// for the number of elements in the base array
for ( $eye = 0; $eye < sizeOf($arr); $eye += 1) {
    // grab each element in the array
    for ( $jay = 0; $jay < sizeOf($arr); $jay += 1) {
        // if the second element of the base array current element
        // is greater than the next one
        if ( $arr[$jay][1] > $arr[$jay + 1][1] ) {
            // then swap those values
            $temp = $arr[$jay]
            $arr[$jay] = $arr[$jay+1]
            $arr[$jay+1] = $temp
        }
    }
}

, , . , , , , .

, , Gale

0

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


All Articles