如何在php中基于键来合并或组合2个数组

时间:2016-07-14 12:22:50

标签: php arrays merge

我有2个阵列,我想合并或组合它们......

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
    )
)
这可能吗?如果有的话,怎么样?....非常感谢

4 个答案:

答案 0 :(得分: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;

试试这段代码..

答案 1 :(得分:0)

尝试:

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

答案 2 :(得分: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

答案 3 :(得分: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
        )

)