我的数组包含从其他函数计算的分数和ID 我有从DB重试的用户信息。
两个数组ID都是相同的 如何将它们推送到一个阵列?
得分数组
Array
(
[0] => Array
(
[id] => 85
[total_cnt] => 2006
)
[1] => Array
(
[id] => 86
[total_cnt] => 1014
)
[2] => Array
(
[id] => 92
[total_cnt] => 6
)
[3] => Array
(
[id] => 93
[total_cnt] => 6
)
)
用户信息
Array
(
[0] => Array
(
[id] => 52
[user_phone] => 00000000
[user_email] => test@yahoo.com
[user_name] => yahoo
[user_picture] =>FG6K7Z3XTc.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 1
[user_reg_date] => 2017-05-16 13:52:35
)
[1] => Array
(
[id] => 78
[user_phone] => 000000001
[user_email] => google@gmail.com
[user_name] => google
[user_picture] =>XqWKSDVci.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 0
[user_reg_date] => 2017-05-16 13:52:35
)
)
我的欲望输出
Array
(
[0] => Array
(
[id] => 86 <--Same ID in both arrays
[user_phone] => 00000000
[user_email] => test@yahoo.com
[user_name] => yahoo
[user_picture] =>FG6K7Z3XTc.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 1
[user_reg_date] => 2017-05-16 13:52:35
[total_cnt] => 1014 <-- first array field added
)
我想要一个优化的代码,但我不会使用循环来执行此操作
感谢您的帮助
答案 0 :(得分:0)
使用PHP的内置函数array_merge
。使用官方PHP文档获取@ http://php.net/manual/en/function.array-merge.php
答案 1 :(得分:0)
更新
更好的方法似乎是“array_column”:
$cnts = array_column($scores, 'total_cnt', 'id');
foreach ($userInfo as $key => $item) {
$userInfo[$key]['total_cnt'] = $cnts[$item['id']];
}
我使用microtime()和测试数据(如阵列)进行了一些“天真”的基准测试:
执行时间: 两个数组中有10000个项目: array_column 0.005s vs 0.85s foreach
两个阵列中的20000项: array_column 0.011s vs 18s foreach
原始答案:
你也可以像这样使用foreach循环:
foreach ($userInfo as $userKey => $item) {
foreach ($scores as $scoreKey => $score) {
if ($score['id'] == $item['id']) {
$userInfo[$userKey]['total_cnt'] = $score['total_cnt'];
unset($scores[$scoreKey]);
break;
}
}
}
第二个循环中的未设置“删除”$ scores数组中的已处理分数,以减少下一次运行中的迭代周期数。请注意,$ scores数组之后将为空,可能会创建一个副本并使用它。