Reputation: 15
I have two 2d arrays and I want to merge them and group their data by a column value.
[
["year" => 2015, "value" => 32],
["year" => 2016, "value" => 54],
]
and
[
["year" => 2015, "value" => 300],
["year" => 2016, "value" => 5400]
]
Desired result:
Array(
[2015]=>array(
[0] => 32
[1] => 95
)
[2016]=>array(
[0] => 54
[1] => 2068
)
)
Upvotes: 1
Views: 313
Reputation: 47894
This can be achieved with a body-less foreach loop using array destructuring syntax. Declare the year
value as a variable, then use it as the first level key when you push the value
value as a new child in the result array.
Code: (Demo)
$result = [];
foreach (array_merge($a, $b) as ['year' => $y, 'value' => $result[$y][]]);
var_export($result);
Upvotes: 0
Reputation: 40896
If the original arrays are $a
and $b
, run this code and the result you want 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'];
}
Upvotes: 1
Reputation: 34914
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);
?>
check here : https://eval.in/605323
output is :
Array
(
[2015] => Array
(
[0] => 32
[1] => 95
)
[2016] => Array
(
[0] => 54
[1] => 2068
)
)
Upvotes: 0
Reputation: 439
$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..
Upvotes: 3
Reputation: 8101
Try:
$newArr = array();
foreach($array1 as $key1=>$arr1) {
$newArr[$arr1['year']][] = $arr1['value'];
$newArr[$arr1['year']][] = $array2[$key]['value'];
}
Upvotes: 0