带有PHP的笛卡尔乘积(id、名称、变体)
你能帮我生成caresian产品吗。 它类似于。我想生成输入,所以我需要保留ID 例如: 我的输入数据:带有PHP的笛卡尔乘积(id、名称、变体),php,associative-array,cartesian-product,Php,Associative Array,Cartesian Product,你能帮我生成caresian产品吗。 它类似于。我想生成输入,所以我需要保留ID 例如: 我的输入数据: [ 1 => [ id => 1, name => "Color", options => [ 5 => [ id => 5, name => "Red" ], 6 => [ id => 6, na
[
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"
]
我需要任何数量的属性/选项的通用函数。嵌套循环人,数组1的每个条目都必须与数组2的每个条目链接 $finalArray=array()
foreach(数组1作为$key1作为$value1){
foreach(数组2作为$key2作为$value2){
回显$value1。“-”$value2。“
”;
$finalArray[$key1.'-'.$key2]=$value1.-“$value2;
}
}
最后一道光线将满足您的需要。这实际上是目前正在运行的代码,但不知道效率有多高
// 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]);
}
}
}
到目前为止你试过什么?请先发布您尝试过的代码,然后我们可以看到您的错误所在。我尝试了上面编写的其他stackoverflow解决方案,但这不是我的目的。我需要动态“函数”来处理任意数量的“属性”。可能有2,3,4。。任何数量带有选项的属性:)都可以使用..只需声明一个新数组并继续放置键和值..让我更新我的答案我明白了,但我不能每次添加新属性时都编辑函数,它必须适用于任何数量的属性。也许我们彼此不了解:)你提到的帖子,你有没有尝试过那种解决方案?我明白你的意思了,你需要动态的数组数量……我试过了。但输出与我的需要不同。:)它结合了所有字段,因此也包括id、名称atc。。这是一个相似的问题,但不同,所以他们的解决方案不适合我的。。
// 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]);
}
}
}