我有以下数组
Array
(
['colour'] => Array
(
[0] => 1130
[1] => 1131
[2] => 1132
[3] => 1133
)
['size'] => Array
(
[0] => 1069
[1] => 1070
)
//there could also be further arrays here such as weight etc
)
我想获得所有可能的排列 - 例如
Colour 1130 - Size 1069
Colour 1130 - Size 1070
Colour 1131 - Size 1069
Colour 1131 - Size 1070
Colour 1132 - Size 1069
etc
但显然不希望每种类型中包含1种以上的排列(一种物品不能同时为蓝色和红色,也不能同时为大中型)
请注意,这些键都是数字键,我在这里将它们更改为颜色,大小以使其更清晰(希望!)
答案 0 :(得分:0)
我从this answer获取了笛卡尔函数,并给出了你想要的输出。
(感谢sergiy创建函数)
<强> https://eval.in/199787 强>
<?php
$array = Array
(
'colour' => Array
(
1130,
1131,
1132,
1133
),
'size' => Array
(
1069,
1070
)
);
echo "<pre>";
$arrFinalArray = cartesian($array);
foreach( $arrFinalArray as $arrIndie) {
//We know each as 2 keys
$arrKeys = array_keys($arrIndie);
$arrValues = array_values($arrIndie);
echo $arrKeys[0] ." ". $arrValues[0] ." - ". $arrKeys[1] ." ". $arrValues[1] ."<br />";
}
echo "</pre>";
function cartesian($input) {
// filter out empty values
$input = array_filter($input);
$result = array(array());
foreach ($input as $key => $values) {
$append = array();
foreach($result as $product) {
foreach($values as $item) {
$product[$key] = $item;
$append[] = $product;
}
}
$result = $append;
}
return $result;
}
答案 1 :(得分:0)
$col = array('color'=>array(1130,1131,1132,1133));
$size = array('size'=>array(1069,1070));
$new_col = array();
foreach($col['color'] as $i=>$c){
$new_col[]= "Color ". $c;
}
$new_size = array();
foreach($size['size'] as $i=>$s){
$new_size[]= "Size ". $s;
}
$new_array = array();
foreach($new_col as $nc){
foreach($new_size as $ns){
$new_array[] = $nc. " ".$ns;
}
}
print_r($new_array);