2012-06-12 75 views
-2

我有2個數組。需要將兩個數組組合/合併成1個數組。我不知道如何去做。我的第一個數組是這樣的:類似的鍵合併陣列

Array 
(
    [A626] => Array 
    (
     [name] => MUHAMMAD FIZMIE ZAKARIA 
     [email] => [email protected] 
     [empid] => A626 
    ) 

    [A672] => Array 
    (
     [name] => MOHD FARID ISMADI 
     [email] => 
     [empid] => A672 
    ) 

    [A1149] => Array 
    (
     [name] => MOHD JAZLI BIN MOHD ZABRI 
     [email] => [email protected] 
     [empid] => A1149 
    ) 

) 

第二個數組是:

Array 
(
    [A1149] => Array 
    (
     [empid] => A1149 
     [online] => 1 
     [ip] => 127.0.0.1 
    ) 

    [A626] => Array 
    (
     [empid] => A626 
     [online] => 0 
     [ip] => 
    ) 

    [A672] => Array 
    (
     [empid] => A672 
     [online] => 0 
     [ip] => 
    ) 

) 

預期的結果應該是這樣的:

Array 
(
    [A626] => Array 
    (
     [name] => MUHAMMAD FIZMIE ZAKARIA 
     [email] => [email protected] 
     [empid] => A626 
     [online] => 0 
     [ip] => 
    ) 

    [A672] => Array 
    (
     [name] => MOHD FARID ISMADI 
     [email] => 
     [empid] => A672 
     [online] => 0 
     [ip] => 
    ) 

    [A1149] => Array 
    (
     [name] => MOHD JAZLI MOHD ZABRI 
     [email] => [email protected] 
     [empid] => A1149 
     [online] => 127.0.0.1 
     [ip] => 1 
    ) 

) 

請幫助我。謝謝

+2

['array_merge_recursive']( http://br.php.net/manual/en/function.array-merge-recursive.php) – bfavaretto

+0

我會認爲接受的答案太複雜,因此不是很有幫助。它可能對你有所幫助,但對你的情況有點太具體。正如你接受它,我會投票結束你的問題,因爲它沒有太大的幫助。 – hakre

回答

0
foreach ($arr1 as $key => $user) { 
    $arr3[$key] = array(
     'name' => $user['name'], 
     'email' => $user['email'], 
     'empid' => $user['empid'], 
     'online' => $arr2[$key]['online'], 
     'ip' => $arr2[$key]['ip'], 
    ); 
} 
+0

非常感謝。非常有幫助 – softboxkid

0

array_merge_recursive確實是that。在你的陣列中,你將在empid上有一個額外的等級,因爲它在兩個陣列上。例如,結果A626

[A626] => Array 
    (
     [name] => MUHAMMAD FIZMIE ZAKARIA 
     [email] => [email protected] 
     [empid] => Array 
      (
       [0] => A626 
       [1] => A626 
      ) 

     [online] => 0 
     [ip] => 
    ) 

你可以忽略這一點,你必須通過獲取父鍵上foreach循環到empid更容易獲得:

foreach($result as $empid=>$data) { 
    // ... 
}