2016-07-14 114 views
0

鍵我有2個數組,我想合併或結合他們...如何合併或合併2個陣列基於其在PHP

Array 
(
    [0] => Array 
     (
      [year] => 2015 
      [value] => 32 
     ) 

    [1] => Array 
     (
      [year] => 2016 
      [value] => 54 
     )  
) 

Array 
(
    [0] => Array 
     (
      [year] => 2015 
      [value] => 95 
     ) 

    [1] => Array 
     (
      [year] => 2016 
      [value] => 2068 
     ) 

) 

我希望他們看起來像這樣...

Array(
    [2015]=>array(
     [0] => 32 
     [1] => 95 
    ) 
    [2016]=>array(
     [0] => 54 
     [1] => 2068 
    ) 
) 

這可能嗎?如果有的話,怎麼....感謝這麼多

+0

[PHP的可能的複製 - 如何合併數組內數組](http://stackoverflow.com/questions/17041278/ph​​p-how-to-merge-arrays-inside-array) – Lekhnath

+1

請先試試看,並分享你的努力。我們在這裏幫助對方學習,而不是做對方的工作。 – BeetleJuice

+1

您可能首先關心的是如何創建這2個數組,然後在該階段創建它們,而不是稍後修復它們, – RiggsFolly

回答

2
$a = array(
    0 => array 
     (
      "year" => 2015, 
      "value" => 32 
     ), 
    1 => array 
     (
      "year" => 2016, 
      "value" => 54 
     ) 
); 

$b = array(
    0 => array 
     (
      "year" => 2015, 
      "value" => 300 
     ), 
    1 => array 
     (
      "year" => 2016, 
      "value" => 5400 
     ) 
); 

$c = array_merge($a,$b); 

$output = array(); 
foreach($c as $key=>$val) 
{ 
    $output[$val['year']][] = $val['value']; 
} 

echo '<pre>'; 
print_r($output); 
exit; 

試試這個代碼..

+0

它的工作....非常感謝你... – user3082963

+0

@ user3082963你真的應該選擇一個答案,如果它解決了你的問題。 – BeetleJuice

0

嘗試:?

$newArr = array(); 
foreach($array1 as $key1=>$arr1) { 
    $newArr[$arr1['year']][] = $arr1['value']; 
    $newArr[$arr1['year']][] = $array2[$key]['value']; 
} 
+0

僅在兩個數組的大小相同或配置相同時才起作用 –

+0

雖然此代碼片段可能會解決這個問題,[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ

0

如果原始陣列$a$b,運行您需要將在$result

$sources = array_merge($a,$b); 
$result = []; 
foreach($sources as $data){ 
    $yr = $data['year']; 
    if(!isset($result[$yr])) $result[$yr]=[]; 
    $result[$yr][]=$data['value']; 
} 
此代碼和結果

Live demo

0

你也可以做這樣的事情,

<?php 
$test1 = [["year"=>2015,"value"=>32],["year"=>2016,"value"=>54]]; 
$test2 = [["year"=>2015,"value"=>95],["year"=>2016,"value"=>2068]]; 

$newarray=array(); 
foreach($test1 as $key1=>$value1){ 
    $temp = [$value1['value']]; 
    foreach($test2 as $key2=>$value2){ 
    if($value1['year']==$value2['year']){ 
    $temp[] = $value2['value']; 
    } 
    $newarray[$value1['year']] = $temp; 
    } 
} 

print_r($newarray); 
?> 

檢查這裏:https://eval.in/605323

輸出爲:

Array 
(
    [2015] => Array 
     (
      [0] => 32 
      [1] => 95 
     ) 

    [2016] => Array 
     (
      [0] => 54 
      [1] => 2068 
     ) 

)