Sort array php [duplicate]

1

I have array , where values are arrays .

How can I order the first array , according to with a value that is in the second array ?

Example:

array(array(id=>5), array(id=>2), array(id=>1), array(id=>3));

What you want is:

array(array(id=>1), array(id=>2), array(id=>3), array(id=>5));
    
asked by anonymous 19.08.2016 / 11:36

1 answer

3

Adapted from this excellent answer in SOen:

$array = array(
    array(
        'id'=>5,
    ),
    array(
        'id'=>2,
    ),
    array(
        'id'=>1,
    ),
    array(
        'id'=>3,
    )
);
usort($array, function($a, $b) {
    return $a['id'] - $b['id'];
});
print_r($array); // Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) [2] => Array ( [id] => 3 ) [3] => Array ( [id] => 5 ) ) 

With PHP 7 we can use the spaceship operator :

usort($array, function($a, $b) {
    return $a['id'] <=> $b['id'];
});
    
19.08.2016 / 11:56