0

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"),
);
1
  • 2
    Have you tried any code yet? Commented Mar 14, 2014 at 17:00

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi! Did my answer help you? I would appreciate if you could accept the answer if it did. Thank you!
2

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.