我有一个包含州代码及其全名的数组,如下所示:
$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"));
答案 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',
),
)