2010-02-18 124 views
0

我有兩個數組需要合併在一起,並試圖找出正確的方法。php將兩個數組合併成一個

這是第一個陣列

Array 
    (
     [IndividualOutmsg] => Array 
      (
       [0] => Array 
        (
         [user_id] => 3 
         [number] => 414566765 
         [msg] => some message 
        ) 

       [1] => Array 
        (
         [user_id] => 3 
         [number] => 410335509 
         [msg] => any message 
        ) 

      ) 

    ) 

這是第二個數組:

Array 
    (
     [0] => Array 
      (
       [0] => OK 
       [1] => 0 
       [2] => d142b46128b869d0 
       [3] => 6178977058476937 
      ) 

     [1] => Array 
      (
       [0] => OK 
       [1] => 0 
       [2] => 60f403f4e243e684 
       [3] => 6198708709873543 
      ) 
    ) 

我想要得到的是這樣的:

Array 
(
    [IndividualOutmsg] => Array 
     (
      [0] => Array 
       (
        [user_id] => 3 
        [number] => 414566765 
        [msg] => some message 
        [sms_status] => OK 
        [error_code] => 0 
        [msg_id] => d142b46128b869d0 
        [msg_id_2] => 6178977058476937 

       ) 

      [1] => Array 
       (
        [user_id] => 3 
        [number] => 410335509 
        [msg] => any message 
        [sms_status] => OK 
        [error_code] => 0 
        [msg_id] => 60f403f4e243e684 
        [msg_id_2] => 6198708709873543 

       ) 

     ) 

) 

回答

1

在這種格式中,你自己真的必須自己做很多合作,不能只用array_merge來組合數組。它必須是一個更多的定製工作,像這樣:

$count = count($second_array); 
for($i=0; $i<$count; $i++){ 
    $first_array['IndividualOutmsg'][$i]['sms_status'] = $second_array[0]; 
    $first_array['IndividualOutmsg'][$i]['error_code'] = $second_array[1]; 
    $first_array['IndividualOutmsg'][$i]['msg_id'] = $second_array[2]; 
    $first_array['IndividualOutmsg'][$i]['msg_id2'] = $second_array[3]; 
} 

如果你要輸出設置的關聯鍵的第二陣列,這將是更容易使用array_merge把它們結合在一起,提供了鑰匙沒」沒有衝突。

$count = count($second_array); 
for($i=0; $i<$count; $i++){ 
    $first_array['IndividualOutmsg'][$i] = 
      array_merge($first_array['IndividualOutmsg'][$i], $second_array[$i]); 
}