1

I have an array which looks like:

array(
    'parent1' => array(
        name = 'somename',
        childs = array('child1', 'child2', 'child3', 'child4')
    ),
    'parent2' => array(
        name = 'somename',
        childs = array('child1')
    ),
    'parent3' => array(
        name = 'somename',
        childs = array('child1', 'child2', 'child3', 'child4', 'child5')
    )
    'parent4' => array(
        name = 'somename',
        childs = array('child1', 'child2', 'child3')
    ),
    'parent5' => array(
        name = 'somename',
        childs = array('child1', 'child2', 'child3', 'child4', 'child5', 'child6', 'child7')
    )
)

Ho do I sort parents by its childs count (asc order)? Parents and childs names should not be changed.

0

4 Answers 4

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


uksort($array, "cmp");
Sign up to request clarification or add additional context in comments.

1 Comment

Steve, if you ask a question, expect responses to it. When you update your question so that it's completely different from the original, it isn't fair to the people who expended effort to give you ultra-fast answers to the original question.
1

Use uasort - it sorts the array and maintains key asscociations (so you won't lose your keys)

uasort($myArray, 'countSort');

function countSort($a, $b) {
    if (count($a['childs']) == count($b['childs'])) {
        return 0;
    }
    
    return (count($a['childs']) < count($b['childs'])) ? -1 : 1;
}

Comments

0

Try this:

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

$test_array = array(
  'parent1' => array('child1', 'child2', 'child3', 'child4'),
  'parent2' => array('child1'),
  'parent3' => array('child1', 'child2', 'child3', 'child4', 'child5'),
  'parent4' => array('child1', 'child2', 'child3'),
  'parent5' => array('child1', 'child2', 'child3', 'child4', 'child5', 'child6', 'child7')
);

print_r($test_array);
usort($test_array, "count_sort");
print_r($test_array);

Comments

0

use uksort:

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

uksort($yourArray, "cmp");

To answer the updated question, you would use uasort() as @fin1te mentioned.

function cmp($a, $b)
{
    return count($a['childs']) - count($b['childs']);
}

uasort($yourArray, "cmp");

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.