Sort a multidimensional array with numeric values

11

Let's suppose the following situation in which I have array composed of several array with numerical values:

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

I would 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?

    
asked by anonymous 31.01.2014 / 17:05

3 answers

11

Use the asort () function:

  

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

Example:

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

asort($array);

Result:

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)
  }
}
    
31.01.2014 / 17:13
0

Try this:

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

Anything goes for something here: Link

    
31.01.2014 / 17:12
0

Another way would also be to use the uasort function, where you sort array according to a last callback. We use count in array internally compared callback to determine which position is to 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 sort it as follows:

 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 this:

 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,
  ),
)
    
19.05.2016 / 13:58