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‘ ) );
PHP5.5支持一个很棒的函数array_column()
非常适合干这个事情,具体请参考手册:http://cn2.php.net/manual/zh/function.array-column.php。
$shop_name = array_column($arr2, ‘shop_name‘, ‘id‘); foreach($arr as $key => $item) { $exist = array_key_exists($item[‘id‘], $shop_name); $arr[$key][‘shop_name‘] = $exist ? $shop_name[$item[‘id‘]] : ‘‘; }
原文地址:https://www.cnblogs.com/wrld/p/10966190.html
时间: 2024-10-07 02:50:27