Home >Backend Development >PHP Tutorial >php-框架 - PHP数组遍历 sku属性值配对

php-框架 - PHP数组遍历 sku属性值配对

WBOY
WBOYOriginal
2016-06-06 20:36:101219browse

<code>    $skuattr = Array
    (
        '7' => Array
            (
                '6' => '22x33',
                '9' => '44x55',
            ),

        '8' => Array
            (
                '12' => '大小号'
            ),

        '9' => Array
            (
                '8' => '金属质',
                '13' => '塑料',
            ),

        '16' => Array
            (
                '14' => '圆形'
            )

    );
</code>

得到4个值
7:6;8:12;9:8;16:14;
7:9;8:12;9:8;16:14
7:6;8:12;9:13;16:14
7:9;8:12;9:13;16:14
因为键值是动态的,所以需要一个数组遍历的算法,得到结果,大神求助

回复内容:

<code>    $skuattr = Array
    (
        '7' => Array
            (
                '6' => '22x33',
                '9' => '44x55',
            ),

        '8' => Array
            (
                '12' => '大小号'
            ),

        '9' => Array
            (
                '8' => '金属质',
                '13' => '塑料',
            ),

        '16' => Array
            (
                '14' => '圆形'
            )

    );
</code>

得到4个值
7:6;8:12;9:8;16:14;
7:9;8:12;9:8;16:14
7:6;8:12;9:13;16:14
7:9;8:12;9:13;16:14
因为键值是动态的,所以需要一个数组遍历的算法,得到结果,大神求助

原理就是要求笛卡尔积,写了一个简单的例子

<code>php</code><code>function combineDika($data) {
    $result = array();
    foreach (array_shift($data) as $k=>$item) {
        $result[] = array($k=>$item);
    }


    foreach ($data as $k => $v) {
        $result2 = [];
        foreach ($result as $k1=>$item1) {
            foreach ($v as $k2=>$item2) {
                $temp     = $item1;
                $temp[$k2]   = $item2;
                $result2[] = $temp;
            }
        }
        $result = $result2;
    }
    return $result;
}

$skuattr = Array
(
    '7'  => Array
    (
        '6' => '22x33',
        '9' => '44x55',
    ),

    '8'  => Array
    (
        '12' => '大小号'
    ),

    '9'  => Array
    (
        '8'  => '金属质',
        '13' => '塑料',
    ),

    '16' => Array
    (
        '14' => '圆形'
    )

);

$a = combineDika($skuattr);
print_r($a);
</code>
<code>php</code><code>Array
(
    [0] => Array
        (
            [6] => 22x33
            [12] => 大小号
            [8] => 金属质
            [14] => 圆形
        )

    [1] => Array
        (
            [6] => 22x33
            [12] => 大小号
            [13] => 塑料
            [14] => 圆形
        )

    [2] => Array
        (
            [9] => 44x55
            [12] => 大小号
            [8] => 金属质
            [14] => 圆形
        )

    [3] => Array
        (
            [9] => 44x55
            [12] => 大小号
            [13] => 塑料
            [14] => 圆形
        )

)
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn