2014-01-17 93 views
0

多維數組假設我有一個多維數組:PHP - 合併基於鍵

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; 

}

+0

具有唯一鍵的值具有額外的逗號。是不是重要? – sectus

回答

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); 
+0

這太棒了!謝謝 –