php合并相同id的两个数组示例代码

php合并相同id的两个数组示例代码,详细代码如下: ?php//数组一$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(

php合并相同id的两个数组示例代码,详细代码如下:
<?php
//数组一
$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为空,形成如下数组:编程学习 topstudy点com点cn
$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'
)
);
//实现代码如下:
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);

本文标题为:php合并相同id的两个数组示例代码

基础教程推荐