PHP合并两个关联的多维数组

时间:2014-08-06 13:07:25

标签: php arrays merge cartesian

我发现很多这样的话题,但我的问题有点不同。 我需要来自两个完全不同的阵列的笛卡儿。第一个数组:

array(2) {
[0] => array(2) { ["value1"] => "some data1", ["value2"] => "some data2"]}
[1] => array(2) { ["value1"] => "some data3", ["value2"] => "some data4"]}
}

和第二个数组

array(3) {
[0] => array(3) { ["value3"] => "some data5", ["value4"] => "some data6", ["value5"] => "some data7"]}
[2] => array(3) { ["value3"] => "some data8", ["value4"] => "some data9", ["value5"] => "some data10"]}
[3] => array(3) { ["value3"] => "some data11", ["value4"] => "some data12", ["value5"] => "some data13"]}
}

有人知道如何从阵列中获取笛卡尔积吗?

1 个答案:

答案 0 :(得分:0)

你不能尝试嵌套for循环吗?

<?php
// NOTICE: Using PHP 5.4 array notation
/**
 * Creates the cartisan product of 2 arrays
 *
 * @param Array $array1, the first array
 * @param Array $array2, the second array
 * @param Callable $operation, the function to call to merge the values from array 1 and 2
 * @returns Array, the cartisian product representation of the 2 arrays with the $operation
 *                 applied
 */
function CartisianArray($array1, $array2, $operation) {
    $ret = [];

    foreach($array1 as $row => $value1) {
      foreach($array2 as $col => $value2) {
        if (!isset($ret[$row])) {
            $ret[$row] = [];
        }
        // Apply the $operation to the values
        $ret[$row][$col] = $operation($value1, $value2);
      }
    }

    return $ret;
}

然后称之为:

$result = CartisianArray($array1, $array2, function($v1, $v2) {
             return $v1 + $v2; // you can define your own operation, here just merging values
});

您没有告诉您想要使用这些值进行哪些操作,所以我只是将它们合并,但您可以轻松更改它。