我有這樣的陣列,我用它作爲INPUT:笛卡爾積 - PHP
Array
(
[0] => Array
(
[11134] => 3.430
[11131] => 2.720
[11128] => 1.077
)
[1] => Array
(
[11135] => 2.381
[11132] => 2.636
[11129] => 2.920
)
[2] => Array
(
[11136] => 1.220
[11133] => 2.550
[11130] => 3.895
)
)
我需要打印該數組的笛卡爾乘積。我使用了位於here的答案,但它對我毫無幫助。我已經修改了喬恩發佈,使其更快的功能(實際上只是交換array_shift
爲array_pop
所以它不會重新索引數組作爲數字):
function cartesian($input) {
$result = array();
while (list($key, $values) = each($input)) {
if (empty($values)) {
continue;
}
if (empty($result)) {
foreach($values as $value) {
$result[] = array($key => $value);
}
}
else {
$append = array();
foreach($result as &$product) {
$product[$key] = array_pop($values);
$copy = $product;
foreach($values as $item) {
$copy[$key] = $item;
$append[] = $copy;
}
$values[] = $product[$key];
}
$result = array_merge($result, $append);
}
}
return $result;
}
給出打印以下數組答案:
Array
(
[0] => Array
(
[0] => 3.430
[1] => 2.920
[2] => 3.895
)
[1] => Array
(
[0] => 2.720
[1] => 2.920
[2] => 3.895
)
...
)
這不是我真正想要的。 功能所需的輸出是:
Array
(
[0] => Array
(
[11134] => 3.430
[11129] => 2.920
[11130] => 3.895
)
[1] => Array
(
[11131] => 2.720
[11129] => 2.920
[11130] => 3.895
)
...
)
我想出瞭如何使我的新數組的第一個元素看起來像我需要的部分代碼如下:
if (empty($result)) {
foreach($values as $key => $value) {
$result[] = array($key => $value);
}
}
但這就是我卡住的地方。我無法獲得其他值來獲取它們的鍵並顯示爲鍵。我設法得到的最後一個數組看起來像這樣。
Array
(
[0] => Array
(
[11134] => 3.430
[1] => 2.920
[2] => 3.895
)
[1] => Array
(
[11131] => 2.720
[1] => 2.920
[2] => 3.895
)
...
)