PHP (id, name, variants) 的笛卡尔积
cartesian product with PHP (id, name, variants)
你能帮我生成 caresian 产品吗?
它类似于 this Whosebug。我想生成输入,所以我需要保留 ID。
示例:
我的输入数据:
[
1 => [
id => 1,
name => "Color",
options => [
5 => [
id => 5,
name => "Red"
],
6 => [
id => 6,
name => "Blue"
]
]
],
2 => [
id => 2,
name => "Size",
options => [
7 => [
id => 7,
name => "S"
],
8 => [
id => 8,
name => "M"
]
]
],
// etc
]
我期望的结果:
[
"5-7" => "Red / S",
"5-8" => "Red / M",
"6-7" => "Blue / S",
"6-8" => "Blue / M"
]
我需要任意数量的通用函数 properties/options..
嵌套循环人,数组 1 的每个条目都必须与数组 2 的每个条目链接。
$finalArray = array();
foreach (array1 as $key1 as $value1){
foreach (array2 as $key2 as$value2){
echo $value1 . " - " .$value2."<br/>";
$finalArray[$key1.'-'.$key2] = $value1 ." - ".$value2;
}
}
finalArray 将满足您的需求。
这实际上是目前有效的代码,但不知道效率如何。
// filter out properties without options
$withOptions = array_filter($properties, function($property) {
return count($property['options']) > 0;
});
$result = [];
$skipFirst = true;
foreach ($withOptions as $property) {
if ($skipFirst) {
foreach (reset($withOptions)['options'] as $id => $option) {
$result[$id] = $option['name'];
}
$skipFirst = false;
continue;
}
foreach ($result as $code => $variant) {
foreach ($property['options'] as $id => $option) {
$new = $code . "-" . $id;
$result[$new] = $variant . " / " . $option['name'];
unset($result[$code]);
}
}
}
你能帮我生成 caresian 产品吗? 它类似于 this Whosebug。我想生成输入,所以我需要保留 ID。
示例:
我的输入数据:
[
1 => [
id => 1,
name => "Color",
options => [
5 => [
id => 5,
name => "Red"
],
6 => [
id => 6,
name => "Blue"
]
]
],
2 => [
id => 2,
name => "Size",
options => [
7 => [
id => 7,
name => "S"
],
8 => [
id => 8,
name => "M"
]
]
],
// etc
]
我期望的结果:
[
"5-7" => "Red / S",
"5-8" => "Red / M",
"6-7" => "Blue / S",
"6-8" => "Blue / M"
]
我需要任意数量的通用函数 properties/options..
嵌套循环人,数组 1 的每个条目都必须与数组 2 的每个条目链接。
$finalArray = array();
foreach (array1 as $key1 as $value1){
foreach (array2 as $key2 as$value2){
echo $value1 . " - " .$value2."<br/>";
$finalArray[$key1.'-'.$key2] = $value1 ." - ".$value2;
}
}
finalArray 将满足您的需求。
这实际上是目前有效的代码,但不知道效率如何。
// filter out properties without options
$withOptions = array_filter($properties, function($property) {
return count($property['options']) > 0;
});
$result = [];
$skipFirst = true;
foreach ($withOptions as $property) {
if ($skipFirst) {
foreach (reset($withOptions)['options'] as $id => $option) {
$result[$id] = $option['name'];
}
$skipFirst = false;
continue;
}
foreach ($result as $code => $variant) {
foreach ($property['options'] as $id => $option) {
$new = $code . "-" . $id;
$result[$new] = $variant . " / " . $option['name'];
unset($result[$code]);
}
}
}