简体   繁体   中英

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

i have 2 array and i want to merge or combine them...

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

it this possible? if ever, how?.... thanks so much

 $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..

Try:

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

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'];
}

Live demo

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
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM