0

I need to sort my array-based on the number of elements in the inner array. It's my current array.

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [0] => 2-3
        )

    [2] => Array
        (
            [0] => 5-9
        )

    [3] => Array
        (
            [0] => 5-9
            [1] => 2-3
        )

)

I need to sort the array by this format.

Array
(
[3] => Array
        (
            [0] => 5-9
            [1] => 2-3
        )

    [2] => Array
        (
            [0] => 5-9
        )

    [1] => Array
        (
            [0] => 2-3
        )

[0] => Array
        (
        )

)

2 Answers 2

2

This seems to do it:

<?php

$a = [
   [], ['2-3'], ['5-9'], ['5-9', '2-3']
];

$f = fn ($b, $c) => count($c) <=> count($b);
usort($a, $f);
print_r($a);

https://php.net/function.usort

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

Comments

1

i hope this answer help you

$result  = array();
$sorter  = array();
foreach($values as $key => $vals){
  $sorter[$key]= count($vals);
}
arsort($sorter);
foreach ($sorter as $ii => $va) {
  $result[$ii]=$values[$ii];
}

output enter image description here

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.