面试题:001
需求:
两个数组
$arr_1 = [
['goods_id'=>100,'goods_name'=>'商品a'],
['goods_id'=>101,'goods_name'=>'商品b'],
['goods_id'=>102,'goods_name'=>'商品c'],
['goods_id'=>103,'goods_name'=>'商品d'],
['goods_id'=>104,'goods_name'=>'商品e'],
];
$arr_2 = [
['goods_id'=>100,'date'=>'2018-07-11'],
['goods_id'=>103,'date'=>'2018-07-10'],
['goods_id'=>104,'date'=>'2018-07-11'],
['goods_id'=>105,'date'=>'2018-07-09'],
];
需求: 把数组组合成,如下
[
['goods_id'=>100,'goods_name'=>'商品a','date'=>'2018-07-11'],
['goods_id'=>101,'goods_name'=>'商品b'],
['goods_id'=>102,'goods_name'=>'商品c'],
['goods_id'=>103,'goods_name'=>'商品d','date'=>'2018-07-10'],
['goods_id'=>104,'goods_name'=>'商品e','date'=>'2018-07-11'],
]
不能使用两层循环,效率低
答案:
$arr_1 = [
['goods_id'=>100,'goods_name'=>'商品a'],
['goods_id'=>101,'goods_name'=>'商品b'],
['goods_id'=>102,'goods_name'=>'商品c'],
['goods_id'=>103,'goods_name'=>'商品d'],
['goods_id'=>104,'goods_name'=>'商品e'],
];
$arr_2 = [
['goods_id'=>100,'date'=>'2018-07-11'],
['goods_id'=>103,'date'=>'2018-07-10'],
['goods_id'=>104,'date'=>'2018-07-11'],
['goods_id'=>105,'date'=>'2018-07-09'],
];
// 转换$arr_2
$new_arr = array_column($arr_2,'date','goods_id');
foreach($arr_1 as $key=>$value){
if(array_key_exists($value['goods_id'],$new_arr)){
$arr_1[$key]['date'] = $new_arr[$value['goods_id']];
}
}
echo '<pre>';
var_dump($arr_1);
PHP面试题-答案
最新推荐文章于 2024-07-04 09:10:45 发布