Finding cartesian product with PHP associative arrays

前端 未结 10 2070
醉梦人生
醉梦人生 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 05:03

    Why not use a recursive generator ... memory issues: close to none
    (and it´s beautiful)

    function cartesian($a)
    {
        if ($a)
        {
            if($u=array_pop($a))
                foreach(cartesian($a)as$p)
                    foreach($u as$v)
                        yield $p+[count($p)=>$v];
        }
        else
            yield[];
    }
    

    note: this does not preserve keys; but it´s a start.

    This should do (not tested):

    function acartesian($a)
    {
        if ($a)
        {
            $k=end(array_keys($a));
            if($u=array_pop($a))
                foreach(acartesian($a)as$p)
                    foreach($u as$v)
                        yield $p+[$k=>$v];
        }
        else
            yield[];
    }
    

提交回复
热议问题