A multi-dimensional array product method

Before writing taobao related business, saw a fairy code, probably the logic is, if the commodity has 1 SKU attributes to do a single layer cycle, if the commodity has 2 SKU attributes to do a double layer cycle, if the commodity has 3 SKU attributes to do a double layer cycle… I was thinking, if a product has 4, 5, 6 skU attributes (unlikely to be any more than that), then I would have to write several more layers of loop. Writing such code would have been a death wish. After running it several times in PHP online, I finally succeeded

And the idea is,

If I have three arrays, respectively [1, 2], [‘ a ‘, ‘b’], [‘ a ‘, ‘b’] — — — — — 2 * 2 * 2 finally concluded that the array should be eight

Step 1: calculate the first array [1, 2] and the second array (‘ a ‘, ‘b’) — — — — — the product of this step is to draw a new array [[1, ‘1’], [1, ‘b’], [2, ‘a’], [2, ‘b’]]

The second step: With the first step of the new array [[1, ‘1’], [1, ‘b’], [2, ‘a’], [2, ‘b’]] with a third array obtained product [‘ a ‘, ‘b’] 4 * 2 finally concluded that the array should be 8 — — — — — [[1,’a’,’A’],[1,’a’,’B’],[1,’b’,’A’],[1,’b’,’B’],[2,’a’,’A’],[2,’a’,’B’],[2,’b’,’A’],[2,’b’,’B’]]

If there are more arrays, and so on…

You can get a lot more output with this method, and I ended up with a concatenated array because I needed to use this format, so you can also manipulate complex data, including obj.

    /** * Product of multiple arrays. * cases: Input [[{' a ':' 1 ', 'b', '2'}]. [{' A ':' 1 ', 'B', '2'}, {' C ', '3', 'D', '4'}]] * output [[{' A ':' 1 ', 'B', '2'}, {' A ':' 1 ', 'B', '2'}], [{' A ':' 1 ', 'B', '2'}, {' C ', '3', 'D', '4'}] ] *@author CitrusLimonc
     * @param array $arrays
     * @return array
     */
    function getArrByArrays($arrays){
        $lastArr = array(a);for ($i=0; $i < count($arrays); $i{+ +)if (count($lastArr) = =0) {
                $lastArr = $arrays[$i];
            }
            if ($i < count($arrays) - 1) {
                $nextArr = $arrays[$i + 1];
            } else {
                break;
            }
            $lastArr = $this->getNextValue($lastArr.$nextArr);
        }
        return $lastArr;
    }
    function getNextValue($lastArr.$nextArr){
        $newArr = array(a);for($i=0; $i< count($lastArr); $i{+ +)for($j = 0; $j< count($nextArr); $j{+ +)$v1 = $lastArr[$i];
                $v2 = $nextArr[$j];
                if (is_array($v1)) {
                    $v1[] = $v2;
                    $value = $v1;
                } else {
                    $value = array(a);$value[] = $v1;
                    $value[] = $v2;
                }
                $newArr[] = $value; }}return $newArr;
    }
Copy the code