How to combine or merge 2 arrays based on their keys in php

I have 2 arrays and I want to combine them or combine ...

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 ) ) 

I want them to look like this ...

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

Is it possible? if ever how? .... thanks a lot

0
source share
4 answers
  $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; 

Try this code ..

+2
source

Try:

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

If the source arrays are $a and $b , run this code and the desired result will be in $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
source

You can also do something like this,

 <?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); ?> 

here: https://eval.in/605323

:

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

All Articles