Finding cartesian product with PHP associative arrays

前端 未结 10 1862
醉梦人生
醉梦人生 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:52

    In PHP 7 @Serg's answer can be shortened to:

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

提交回复
热议问题