Jan
Jan

Reputation: 582

Sort multidimensional array with two arrays inside?

I would like to sort my array according to a value which is represented by another array. So, this right here is my array:

Array
(
    [0] => Array
        (
            [0] => 13.31421
            [1] => WP_Post Object (...)
        )
    [1] => Array
        (
            [0] => 4.213
            [1] => WP_Post Object (...)
        )
    [2] => Array
        (
            [0] => 144.314
            [1] => WP_Post Object (...)
        )
)

I would like to sort my array by number on index 0 which you can see e.g. at the index: [0][0] = 13.31421.

I already tried to find some answers on google but the solutions didn't really work out:

uasort($post_distance, function($a, $b) {
    return $a[0] - $b[0];
});

Upvotes: 1

Views: 26

Answers (1)

Djellal Mohamed Aniss
Djellal Mohamed Aniss

Reputation: 1733

try to use the usort function.

usort ( array &$array , callable $value_compare_func ) : bool

add this method to your code

function compare($a, $b)
{
    if ( $a[0] == $b[0] ) {
        return 0;
    }
    return ( $a[0] < $b[0] ) ? -1 : 1;
}

then simply call the usort function

usort($post_distance,"compare");

Upvotes: 1

Related Questions