Sort a multidimensional array with numerical values

Asked

Viewed 1,814 times

11

Suppose the following situation in which I have a array composed of several array numerically valued:

$array = array(
    array(22, 25, 28),
    array(22),
    array(22, 23)
)

I’d like to leave this array ordered as follows:

$array = array(
    array(22),
    array(22, 23),
    array(22, 25, 28)
)

What would be the algorithm for this case?

3 answers

11


Use the function asort():

This function sorts an array so that the correlation between indices and values is maintained. It is mainly used to sort associative arrays where the order of the elements is an important factor.

Example:

$array = array(
   array(22, 25, 28),
   array(22),
   array(22, 23)
);

asort($array);

Upshot:

var_dump($array);

array(3) {
  [1]=>
  array(1) {
    [0]=>
    int(22)
  }
  [2]=>
  array(2) {
    [0]=>
    int(22)
    [1]=>
    int(23)
  }
  [0]=>
  array(3) {
    [0]=>
    int(22)
    [1]=>
    int(25)
    [2]=>
    int(28)
  }
}

0

Another way would also be using the function uasort, where you order the arrayaccording to a past callback. We use count us array internally compared the callback to determine which position will be ordered.

Let’s imagine the following array:

$a = array (
  0 => 
  array (
    0 => 1,
    1 => 2,
  ),
  1 => 
  array (
    0 => 1,
  ),
  2 => 
  array (
    0 => 1,
    1 => 3,
    2 => 4,
    3 => 5,
  ),
  3 => 
  array (
    0 => 1,
    1 => 3,
  ),
);

We could order it like this:

 uasort($a, function ($a, $b) { 
     return count($a) - count($b);
 })

The result would be:

array (
  1 => 
  array (
    0 => 1,
  ),
  0 => 
  array (
    0 => 1,
    1 => 2,
  ),
  3 => 
  array (
    0 => 1,
    1 => 3,
  ),
  2 => 
  array (
    0 => 1,
    1 => 3,
    2 => 4,
    3 => 5,
  ),
)

If you wanted this result in reverse order, you could do so:

 uasort($a, function ($a, $b) { 
     return count($b) - count($a);
 })

 print_r($a);

The result would be:

array (
  2 => 
  array (
    0 => 1,
    1 => 3,
    2 => 4,
    3 => 5,
  ),
  3 => 
  array (
    0 => 1,
    1 => 3,
  ),
  0 => 
  array (
    0 => 1,
    1 => 2,
  ),
  1 => 
  array (
    0 => 1,
  ),
)

0

Try this:

array_multisort($array);
print_r($array);

Something’s looking for something around here: Link

Browser other questions tagged

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