1

I have a function that finds all the possible combinations of an array:

function combination($array) 
{    
    $results = array(array());

    foreach ($array as $element)
        foreach ($results as $combination)
            array_push($results, array_merge(array($element), $combination));

    return $results;
}

This returns a multidimensional array and it works.

If I try to print the array, I use this:

foreach (combination($set)  as $combination)
{
    print join("\t", $combination) . "  - ";
}

For: $set = array('s','f','g');

The output is: - s - f - f s - g - g s - g f - g f s -

Now what I cant figure out is how can I sort the combinations according to length in a way where the output becomes: - g f s - g s - g f - f s - g - s - f -

1

1 Answer 1

3

you need to use 'usort' for this:

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

$result = combination($set);

usort($result, 'sortByLength');

you could also just use 'sortByLength' as an anonymous function, instead of defining it, if you use this only once:

$result = combination($set);

usort($result, function($a, $b) {
    return count($b) - count($a);
} );
Sign up to request clarification or add additional context in comments.

6 Comments

Thats right but Im not trying to sort $set, I am trying to sort combination($set).
just save the result of combination($set) in a variable - i edited the example for you
your script works with a 1 dimensional array, combination($set) is a multidimensional array
can you post the array structure of the multidimensional array? does the sorted array have to stay multidimensional, or one-dimensional?
for that, you basically only need to change strlen() to count() - it even would stay multidimensional that way. I'll edit it in.
|

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.