php將兩個數組相同的key合並到一個數組


$arr = array(
    array(
    'id' => 1,
    'user_name'=>'test1'
    ),
    array(
    'id' => 2,
    'user_name'=>'test2'
    ),
    array(
    'id' => 3,
    'user_name'=>'test3'
    )
);
$arr2 = array(
     array(
    'id' => 1,
    'shop_name'=>'shop1'
    ),
    array(
    'id' => 5,
    'shop_name'=>'shop2'
    ),
    array(
    'id' => 3,
    'shop_name'=>'shop3'
    )
);
怎么根據2個數組id相同的一維數組,將$arr2的shop_name添加到$arr,如果沒有相同的id,shop_name為空,形成如下數組:
$good_arr =array(
    array(
    'id' => 1,
    'user_name'=>'test1',
    'shop_name'=>'shop1'
    ),
    array(
    'id' => 2,
    'user_name'=>'test2',
    'shop_name'=>''
    ),
    array(
    'id' => 3,
    'user_name'=>'test3',
    'shop_name'=>'shop3'
    )

);
1. foreach($arr as $k2 =>&$v2) {
$v2['shop_name']='';

foreach($arr2 as $k =>$v) {

   if($v2['id'] == $v['id']) {

$v2['shop_name'] = $v['shop_name'];

}

}

}

print_r($arr);

2. 


$tempArr = array();
foreach($arr2 as $item) 
    $tempArr[$item['id']] = $item['shop_name'];

foreach($arr as $k => $v) {
    if(array_key_exists($v['id'], $tempArr)) { 
        $arr[$k]['shop_name'] = $tempArr[$v['id']];
    } else {
        $arr[$k]['shop_name'] = '';
    }
}
$newArr = $arr;
3.

$tmp = '';
foreach ($arr2 as $k) { $tmp[$k['id']] = $k; }
foreach ($arr as &$v) {
    $sn = $tmp[$v['id']]['shop_name'];
    $sn = $sn ? $sn :'';
    $v['shop_name'] = $sn;
}

var_dump($arr);

?>
4.
$shop_name = array_column($arr2, 'shop_name', 'id');//方便減少foreach

foreach($arr as $key => $item) {
    $exist = array_key_exists($item['id'], $shop_name);
    $arr[$key]['shop_name'] = $exist ? $shop_name[$item['id']] : '';
}
print_r($arr);

 


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM