2017-06-28 9 views
-1

他の関数から計算されたスコアとIDを含む配列を持っています そして、私はDBから再試行したユーザー情報を持っています。PHPで多次元配列にプッシュ

両方の配列IDは同じ どのように1つの配列にプッシュできますか?

スコアアレイ

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

使用PHPの組み込み関数array_mergeのために、この

感謝を行うにするために、私は、ループを使用しません。私が)のmicrotimeを使用して、いくつかの "ナイーブ" ベンチマークテストを(作っ

$cnts = array_column($scores, 'total_cnt', 'id'); 
foreach ($userInfo as $key => $item) { 
    $userInfo[$key]['total_cnt'] = $cnts[$item['id']]; 
} 

よりよい方法は "array_column" のようだ:http://php.net/manual/en/function.array-merge.php

+0

更新を参照してください、 –

0

更新@追加のガイダンスのための公式のPHPのマニュアルを使用しますあなたの配列のようなテストデータ:

実行時間:両方の配列で 10000件のアイテム:0.85s foreachの対0.005s array_column

両方の配列で件の

20000アイテム: 18S対0.011s array_column 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; 
     } 
    } 
} 

また、foreachのは、このようにループを使用することができます次の実行で反復サイクル数を減らすために、$ score配列から処理されたスコアを削除します。 $ score配列は後で空になります。おそらく、そのコピーを作成してそれを処理してください。

+0

いいえ、コードの実行時間が高すぎるため、最悪の方法です –

+0

残念ながら動作しません –

+0

どうしてですか?実際の使用例:https://eval.in/823485 – user1915746