如何从两个子阵列生成值的组合?

时间:2015-02-20 09:32:44

标签: php arrays loops combinations cartesian-product

我有两个这样的子阵列

Array
(
    [0] => Array
        (
            [id] => 17
            [name] => Color
            [value] => White,Black
            [attribute_id] => 1
        )

    [1] => Array
        (
            [id] => 15
            [name] => Size
            [value] => L,S,M,XL,XXL,XXXL
            [attribute_id] => 5
        )

)

我想生成价值元素的组合'数据

预期结果:

White L
White S
White M
White XL
White XXL
White XXXL
Black L
Black S
Black M
Black XL
Black XXL
Black XXXL

我已尝试过foreach,但无法做到。

1 个答案:

答案 0 :(得分:0)

只需使用explode()即可。请使用以下代码:

<?php
// Your array:
$array = array(array("id"=>17,"name" => "Color","value" => "White,Black","attribute_id" => 1),array("id" => 15,"name" => "Size","value" => "L,S,M,XL,XXL,XXXL", "attribute_id" => 5));

$x = explode(",",$array[0]["value"]);
foreach($x as $p=>$k){

    $explode = explode(",",$array[1]["value"]);
    foreach($explode as $pe){
        echo $k." ".$pe."<br>";
    }
}
?>