遇到的问题:
当前有两个数组,已知的是两个数组中,数组1中的id等于数组2中的pid,问题是,要把数组2中的img_url合并到到数组1中对应的id下。
最终需要实现:
Array ( [0] => Array ( [id] => 7 [collection_id] => 1 [prize_num] => 1 [prize_name] => 立减20元 [total] => 10 ,**[url_img]=> /upload/business/1476342419.png** ) [1] => Array ( [id] => 8 [collection_id] => 1 [prize_num] => 2 [prize_name] => 全单8折 [total] => 20,**[url_img]=> /upload/business/1476348963.jpg**)
问题已解决
立即学习“PHP免费学习笔记(深入)”;
<code>先跑第一个循环,在里面跑第二个循环,去第二个数组找符合条件的item
foreach ($shopPrizeName as $key => $value) {
foreach ($shopPImagesName as $k => $v) {
if($value['id'] == $v['pid'])
{
$value['img_url'] = $v['img_url'];
}
}
$shopData[] = $value;
}
print_r($shopData);</code>遇到的问题:
当前有两个数组,已知的是两个数组中,数组1中的id等于数组2中的pid,问题是,要把数组2中的img_url合并到到数组1中对应的id下。
最终需要实现:
Array ( [0] => Array ( [id] => 7 [collection_id] => 1 [prize_num] => 1 [prize_name] => 立减20元 [total] => 10 ,**[url_img]=> /upload/business/1476342419.png** ) [1] => Array ( [id] => 8 [collection_id] => 1 [prize_num] => 2 [prize_name] => 全单8折 [total] => 20,**[url_img]=> /upload/business/1476348963.jpg**)
问题已解决
立即学习“PHP免费学习笔记(深入)”;
<code>先跑第一个循环,在里面跑第二个循环,去第二个数组找符合条件的item
foreach ($shopPrizeName as $key => $value) {
foreach ($shopPImagesName as $k => $v) {
if($value['id'] == $v['pid'])
{
$value['img_url'] = $v['img_url'];
}
}
$shopData[] = $value;
}
print_r($shopData);</code>
看到你自己解决了, 再给你个方法
<code>/**
* 从多维数组中抽取一列'img_url'组成新数组, 并使用多维数组中的id作为key
* 当然你也可以不用array_column自己通过foreach拼接这个数组
*/
$idImgMap = array_column($shopImageName, 'img_url', 'id');
foreach ($shopPrizeName as &$value) {
$value['img_url'] = $idImgMap[$value['id']];
}</code>这个实现的算法复杂度是 2O(n), 你的是O(n^2), 所以这个性能会更好一点
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号