当键存在于另一个数组中时,如何替换多维数组的值?

时间:2017-06-20 11:35:49

标签: php arrays multidimensional-array replace

我有一个包含州代码及其全名的数组,如下所示:

$first_array=array("AB"=>"Alberta","BC"=>"British Columbia");

我有另一个包含id和状态代码的数组,如下所示:

$result_array=array(15=>array("ad_id"=>15,"state code"=>"AB"));

我想将state code中的$result_array值替换为相应的"全名"在$first_array

如果$first_array中没有相应的值,则state code中的$result_array应保持不变。

这是我的预期结果:

$result_array=array(15=>array("ad_id"=>15,"state code"=>"Alberta"));

2 个答案:

答案 0 :(得分:1)

这应该有效 -

$first_array= array("AB"=>"Alberta","BC"=>"British Columbia");

$second_array = array(
15 => array ( 'ad_id' => 15, 'state code' => 'AB' ) ,
16 => array ( 'ad_id' => 16, 'state code' => 'CD' ) 
);

$new = array_map(function($a) use($first_array) {
    return array(
        'ad_id' => $a['ad_id'],
        'state code' => !empty($first_array[$a['state code']]) ? $first_array[$a['state code']] : $a['state code'],
    );
}, $second_array);

print_r($new);

<强>输出

Array
(
    [15] => Array
        (
            [ad_id] => 15
            [state code] => Alberta
        )

    [16] => Array
        (
            [ad_id] => 16
            [state code] => CD
        )

)

答案 1 :(得分:0)

输入:

$first_array=["AB"=>"Alberta","BC"=>"British Columbia"];
$result_array=[
    15=>['ad_id'=>15,'state code'=>'AB'],
    16=>['ad_id'=>16,'state code'=>'BC'],
    17=>['ad_id'=>17,'state code'=>'NY']
];

方法#1 - array_walk()

array_walk($result_array,function(&$a)use($first_array){
    if(isset($first_array[$a['state code']])){  // only overwrite state code if full name is available
        $a['state code']=$first_array[$a['state code']];
    }
});

方法#2 - foreach()

foreach($result_array as $k=>$a){
    if(isset($first_array[$a['state code']])){  // only overwrite state code if full name is available
        $result_array[$k]['state code']=$first_array[$a['state code']];
    }   
}

输出(来自任一方法):var_export($result_array);

array (
  15 => 
  array (
    'ad_id' => 15,
    'state code' => 'Alberta',
  ),
  16 => 
  array (
    'ad_id' => 16,
    'state code' => 'British Columbia',
  ),
  17 => 
  array (
    'ad_id' => 17,
    'state code' => 'NY',
  ),
)