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

前端 未结 8 770
野性不改
野性不改 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 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);
    

提交回复
热议问题