PHP - 基于键合并多维数组

时间:2014-01-17 00:38:37

标签: php arrays merge

假设我有一个多维数组:

Array
(
    [0] => Array
        (
            [7,14] => 0.0,3.0
            [5,11] => 0.0,5.0
            [8,6] => 0.0,6.0
        )

    [1] => Array
        (
            [7,14] => 0.0,1.0
            [5,11] => 1.0,3.0
            [11,13] => 1.0,1.0
            [6,8] => 1.0,0.0

        )

我想形成一个新数组,其中键作为每个数组中所有键的并集,值是这些联合键的对应值。如果只在一个子数组中找到某个键​​,则用逗号填充将要数据

即结果----------

Array
(
             [7,14] => 0.0,3.0,0.0,1.0             // <--- union 0.0,3.0 and 0.0,1.0
             [5,11] => 0.0,5.0,1.0,3.0
             [8,6] => 0.0,6.0,,
             [11,3] => 1,0,1.0,,
             [6,8] => 1.0,0.0,,

)

这是我尝试过的。我非常接近正确答案!

function combineValues($bigArray){

$combinedArray = array();

   for($i = 0; $i < (count($bigArray) - 1); $i++) {


      $keys = array_keys($bigArray[$i]);

      for($j = 0; $j < count($keys); $j++){

            $currentKey = $keys[$j];

        if (isset($bigArray[$i+1][$currentKey]){
            $combinedArray[$currentKey] = $bigArray[$i][$currentKey] + "," + $bigArray[$i+1][$currentKey];
        } else {

        }


    }

  }

  return $combinedArray;

}

1 个答案:

答案 0 :(得分:2)

使用foreach代替for很容易。

$array2 = [[1, 2, 3, 4], [2 => 7, 8, 9]];
$return_array = array();    
foreach ($array2 as $array1)
    {
    foreach ($array1 as $key => $value)
        {
        if (isset($return_array[$key]))
            $return_array[$key].=',' . $value;
        else
            $return_array[$key] = $value;
        }
    }

var_dump($return_array);

您也可以使用语言的功能特性。 array_walk_recursive

$array2 = [[1, 2, 3, 4], [2 => 7, 8, 9]];

$return_array = array();

array_walk_recursive($array2, function ($value, $key)use(&$return_array)
        {
        if (isset($return_array[$key]))
            $return_array[$key].=',' . $value;
        else
            $return_array[$key] = $value;
        });

var_dump($return_array);