假设我有一个数组,如下所示: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);任何帮助都将不胜感激。用PHP关联数组求笛卡儿积
3 回答
ibeautiful
TA贡献1993条经验 获得超5个赞
function inject($elem, $array) { return array_map(function ($n) use ($elem) { return array_merge((array)$elem, (array)$n); }, $array);}function zip($array1, $array2) { return array_reduce($array1, function ($v, $n) use ($array2) { return array_merge($v, inject($n, $array2)); }, array());} function cartesian_product($array) { $keys = array_keys($array); $prod = array_shift($array); $prod = array_reduce($array, 'zip', $prod); return array_map(function ($n) use ($keys) { return array_combine($keys, $n); }, $prod);}
(下面使用伪数组/列表/字典表示法,因为PHP对于这类事情太冗长了。)
inject
a, [b]
[(a,b)]
a
b
inject('a', ['foo', 'bar']) => [('a', 'foo'), ('b', 'bar')]
zip
inject
zip(['a', 'b'], ['foo', 'bar']) => [('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bar')]
zip
zip(zip(['a', 'b'], ['foo', 'bar']), ['42', '76']) => [('a', 'foo', '42'), ('a', 'foo', '76'), ('a', 'bar', '42'), …]
array_combine(['key1', 'key2', 'key3'], ['a', 'foo', '42']) => [ key1 : 'a', key2 : 'foo', key3 : '42' ]
function inject($elem, $array) { $elem = (array)$elem; foreach ($array as &$a) { $a = array_merge($elem, (array)$a); } return $array;}function zip($array1, $array2) { $prod = array(); foreach ($array1 as $a) { $prod = array_merge($prod, inject($a, $array2)); } return $prod;}function cartesian_product($array) { $keys = array_keys($array); $prod = array_shift($array); $prod = array_reduce($array, 'zip', $prod); foreach ($prod as &$a) { $a = array_combine($keys, $a); } return $prod;}
添加回答
举报
0/150
提交
取消