Finding cartesian product with PHP associative arrays

前端 未结 10 1856
醉梦人生
醉梦人生 2020-11-22 04:17

Say that I have an array like the following:

Array
(
    [arm] => Array
        (
            [0] => A
            [1] => B
            [2] => C
         


        
10条回答
  •  清酒与你
    2020-11-22 04:41

    Here is optimized version of @Jon's cartesian function:

    function cartesian($input) {
        $result = array(array());
    
        foreach ($input as $key => $values) {
            $append = array();
    
            foreach($result as $product) {
                foreach($values as $item) {
                    $product[$key] = $item;
                    $append[] = $product;
                }
            }
    
            $result = $append;
        }
    
        return $result;
    }
    

    Read more about the math behind this algorithm: http://en.wikipedia.org/wiki/Cartesian_product

    See more examples of this algorithm in different languages: https://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists

提交回复
热议问题