2011-07-20 146 views
1

我有兩個數組:如何合併兩個數組的值?

$a = array(
    array("id" => 132), 
    array("id" => 131), 
    array("id" => 129), 
    array("id" => 128) 
) 

$b = array(
    array("id" => 129, "attachment_id" => 111), 
    array("id" => 129, "attachment_id" => 112), 
    array("id" => 132, "attachment_id" => 113), 
    array("id" => 132, "attachment_id" => 114), 
    array("id" => 132, "attachment_id" => 115) 
) 

我需要從這兩個一個陣列。 id鍵必須是唯一的,所以不能重複。問題是:我需要在該新陣列中創建一個名爲attachments的新元素,該元素是數組,並且包含idattachment_id的值。你看,可能有更多的attachment_idid

很難解釋,但我希望你能理解!謝謝你的建議。

編輯:

這裏是理想的結果:

$c = array(
    array("id" => 132, 'attachments' => array(113, 114, 115)), 
    array("id" => 131, 'attachments' => array()), 
    array("id" => 129, 'attachments' => array(111, 112)), 
    array("id" => 128, 'attachments' => array()) 
); 

回答

1

喜歡的東西:

$a = array(
    array("id" => 132), 
    array("id" => 131), 
    array("id" => 129), 
    array("id" => 128) 
); 

$b = array(
    array("id" => 129, "attachment_id" => 111), 
    array("id" => 129, "attachment_id" => 112), 
    array("id" => 132, "attachment_id" => 113), 
    array("id" => 132, "attachment_id" => 114), 
    array("id" => 132, "attachment_id" => 115) 
); 

$c = array(); 

foreach ($a as $idEntry) { 
    $tmp = array(
     'id' => $idEntry['id'], 
     'attachments' => array() 
    ); 

    foreach ($b as $bIdx => $attachmentEntry) { 
     if ($attachmentEntry['id'] == $idEntry['id']) { 
      $tmp['attachments'][] = $attachmentEntry['attachment_id']; 
      unset($b[$bIdx]); 
     } 
    } 

    $c[] = $tmp; 
} 

print_r($c); 
+0

它幾乎可以工作!結果是這樣的... http://pastie.org/2242171 – daGrevis

+0

@daGrevis「幾乎」因爲?? :) – Yoshi

+0

請看我的問題的編輯。結果並不像我想要的那樣。 ;( – daGrevis

1

像這樣的東西應該這樣做:

# Temporary array 
$c = array(); 

# Loop through all attachments and index them by id 
foreach($b as $row) { 
    if(!isset($c[$row['id']])) { 
     $c[$row['id']] = array(); 
    } 
    $c[$row['id']][] = $row['attachment_id']; 
} 

# Loop through ids and add attachments where available 
foreach($a as &$row) { 
    $row['attachments'] = isset($c[$row['id']]) ? $c[$row['id']] : array() 
} unset($row); 

輸出:

array(
    array("id" => 132, "attachments" => array(113, 114, 115)), 
    array("id" => 131, "attachments" => array()), 
    array("id" => 129, "attachments" => array(111, 112)), 
    array("id" => 128, "attachments" => array()) 
)