Sort array php

Asked

Viewed 106 times

1

I have a array, in which values are arrays.

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

Example:

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

The intended is:

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

1 answer

3


Adapted from this excellent response in the 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 Spaceship Operator:

usort($array, function($a, $b) {
    return $a['id'] <=> $b['id'];
});
  • 2

    excellent implementation of Spaceship Operator.

  • Obgado @Allanandrade, in fact was adapted from a reply on Soen, I put the link in the reply

  • I can’t get the same scheme to sort by date, that is, where in the array above I have integers, have a datetime (2016-08-25 19:57:28). Is there any simple way to resolve this situation?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.