简体   繁体   中英

All possible combinations for a BIG array in PHP

I am trying for 2 days to create a function to get all possible array combinations (without order repetitions):

 public function power_set($array) {
    // initialize by adding the empty set
    $results = array(array( ));

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

    return $results;
}

$keys = array(0=>1,1=>2,3=>3,21=>4,4=>5,5=>6,6=>7,7=>8,9=>10,10=>23,11=>34234,12=>34234,13=>34234,14=>45435,15=>32343,16=>35324,17=>4535345,18=>5645645,19=>234,20=>23324);

 echo '<pre>'.print_r(power_set($keys),true).'</pre>';

It work fine for a 7 element array, but more than than it dont't. How can I fix it?

John I think this is more of an issue with where you are running the code. As some of the comments on your question indicate, the php shell where you are executing the function has a limited working memory.

I tested with an array length 10, and was returned 1024 items (the correct amount).

Try running it as a file in your console: $ php test_file.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM