Skip to content
Advertisement

how to sort array by inner array size

how to sort array by inner array size?

i want to sort my array by size of array inside. each array that has more items most put at the end and each array has less items most got to top.

note: I want sum of size of all items and sub items.

this is my array:

$myArray = array (
  0 => 
  array (
    'item1' => 80,
    'item2' => 81,
    'item3' => 83,
    'item4' => 84,
  ),
  1 => 
  array (
    'item3' => array (
       'item1' => 85,
       'item2' => 85,
       'item3' => 85,
       'item4' => 85,
       'item5' => 85,
    ),
  ),
  2 => 
  array (
    'item1' => 25,
    'item2' => 22,
    'item3' => 11,
  ),
)

i want this output:

array (
  0 => 
  array (
    'item1' => 25,
    'item2' => 22,
    'item3' => 11,
  ),
  1 => 
  array (
    'item1' => 80,
    'item2' => 81,
    'item3' => 83,
    'item4' => 84,
  ),
  2 => 
  array (
    'item3' => array (
       'item1' => 85,
       'item2' => 85,
       'item3' => 85,
       'item4' => 85,
       'item5' => 85,
    ),
  ),
)

Advertisement

Answer

Array Keys

You can’t have the same unique key repeated in an array

$arr = ["item1" => 1, "item1" => 2];
// Is equivalent to: 
//    $arr = ["item1" => 2];

Your question

Key knowledge:

  • count($array, $recurse = FALSE)
  • usort($array, $function)
  • <=> spaceship operator

Using usort we can use a defined a function to sort the array. The function will be passed two variables to compare at a time and must return <0 | 0 | >0 depending whether a is less than, equal to, or greater than b.

To count the keys in the array we can use the recursive move of count by setting the second parameter to TRUE.

We can then use count inside of our function to count a and b and compare the result.

$array = [
    [1,2,3,4],
    [1,2,[1,2,3,4,5]],
    [1,2,3]
];

function compare_size($a, $b){
    return (count($a, TRUE)<=>count($b, TRUE));
}
usort($array, "compare_size");

echo json_encode($array);


/*
  Output:
    [
      [1,2,3],
      [1,2,3,4],
      [1,2,[1,2,3,4,5]]
    ]
*/


)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement