How to generate in PHP all combinations of items in multiple arrays

前端 未结 8 785
野性不改
野性不改 2020-11-22 07:20

I\'im trying to find all combinations of items in several arrays. The number of arrays is random (this can be 2, 3, 4, 5...). The number of elements in each array is random

相关标签:
8条回答
  • 2020-11-22 07:56

    I got this from O'Relly (https://www.oreilly.com/library/view/php-cookbook/1565926811/ch04s25.html),

    function pc_array_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(array($element), $combination));
    
    
    
       return $results;
    }
    

    Then call it using,

    $set = array('A', 'B', 'C');
    $power_set = pc_array_power_set($set);
    

    That should do the trick!

    0 讨论(0)
  • 2020-11-22 08:01

    One more idea:

    $ar = [
        'a' => [1,2,3],
        'b' => [4,5,6],
        'c' => [7,8,9]
    ];
    
    $counts = array_map("count", $ar);
    $total = array_product($counts);
    $res = [];
    
    $combinations = [];
    $curCombs = $total;
    
    foreach ($ar as $field => $vals) {
        $curCombs = $curCombs / $counts[$field];
        $combinations[$field] = $curCombs;
    }
    
    for ($i = 0; $i < $total; $i++) {
        foreach ($ar as $field => $vals) {
            $res[$i][$field] = $vals[($i / $combinations[$field]) % $counts[$field]];
        }
    }
    
    var_dump($res);
    
    0 讨论(0)
提交回复
热议问题