使用 PHP 关联数组查找笛卡尔积
假设我有一个如下数组:
Array
(
[arm] => Array
(
[0] => A
[1] => B
[2] => C
)
[gender] => Array
(
[0] => Female
[1] => Male
)
[location] => Array
(
[0] => Vancouver
[1] => Calgary
)
)
如何在保留外部关联数组的键并在内部数组中使用它们的同时找到笛卡尔积?算法的结果应该是这样的:
Array
(
[0] => Array
(
[arm] => A
[gender] => Female
[location] => Vancouver
)
[1] => Array
(
[arm] => A
[gender] => Female
[location] => Calgary
)
[2] => Array
(
[arm] => A
[gender] => Male
[location] => Vancouver
)
...etc.
我已经查找了相当多的笛卡尔积算法,但我被困在如何保留关联键的细节上。我使用的当前算法仅给出数字索引:
$result = array();
foreach ($map as $a) {
if (empty($result)) {
$result = $a;
continue;
}
$res = array();
foreach ($result as $r) {
foreach ($a as $v) {
$res[] = array_merge((array)$r, (array)$v);
}
}
$result = $res;
}
print_r($result);
任何帮助将不胜感激。