如何合并两个数组的值?

时间:2011-07-20 10:26:18

标签: php arrays loops merge

我有两个数组:

$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的新数组中创建新元素,该数组包含attachment_id的{​​{1}}值。您看,id可能只有一个attachment_id

很难解释,但我希望你能理解!谢谢你的建议。

修改

这是理想的结果:

id

3 个答案:

答案 0 :(得分: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())
)

答案 1 :(得分: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);

答案 2 :(得分:-1)

按'id'索引数组,然后使用http://php.net/manual/en/function.array-merge.php