2017-06-28 122 views
-1

我有一个数组,其中包含从其他函数计算的分数和ID 而且我有从DB重试的用户信息。推到多维数组php

在这两个数组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] => [email protected] 
      [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] => [email protected] 
      [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] => [email protected] 
       [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 
      ) 

我想要一个的Optim美化版代码,我不会用回路来对你的帮助

回答

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的foreach 18S

原来的答复:

您还可以使用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数组将在之后为空,也许会创建一个副本并使用它。

+0

不,它是一种最糟糕的方式,因为代码的执行时间很长 –

+0

不幸的是没有工作 –

+0

为什么不呢?工作示例:https://eval.in/823485 – user1915746