erin
erin

Reputation: 1160

sort array of arrays by number of elements in sub array

I have an array of arrays. I want to sort the containing array so that the sub arrays with the most elements in the array are first.

Example:

$my_array = array(
  array(0=>”a", 1=>”b”, 4=>”c"),
  array(3=>”z"),
  array(0=>”p”, 2=>”k"),
);

Desired result: The sub array with 3 elements is ordered 1st and the sub array with 1 element is ordered last.

$my_array = array(
  array(0=>”a", 1=>”b”, 4=>”c"),
  array(0=>”p”, 2=>”k"),
  array(3=>”z"),
);

Upvotes: 0

Views: 142

Answers (2)

Marc
Marc

Reputation: 426

A variant of this might do the trick. usort

function compare($a, $b) {
  if (count($a) == count($b)) return 0;
  return (count($a) < count($b)) ? -1 : 1;
}

usort($my_array, 'compare');

Upvotes: 2

Just use usort() with the count() method.

<?php

$my_array = array(
  array(0=>"a", 1=>"b", 4=>"c"),
  array(3=>"z"),
  array(0=>"p", 2=>"k"),
);

usort($my_array, function($a, $b) {
    if (count($a) == count($b)) {
        return 0;
    }
    return (count($a) < count($b)) ? 1 : -1;
});

print_r($my_array);

Example fiddle

Upvotes: 4

Related Questions