I have two ar开发者_Go百科rays:
$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)
)
I need to make one array from those two. id
key must be unique so it can't be repeated. Problem is that: I need to make new element in that new array called attachments
that's array and contains values of attachment_id
for that id
. You see, there may be more that one attachment_id
for id
.
Its hard to explain, but I hope that you'll understand! Thanks in advice.
Edit:
Here is desired outcome:
$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())
);
Something like:
$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);
Something like this should do it:
# 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);
Output:
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())
)
Index your arrays by 'id' and then use http://php.net/manual/en/function.array-merge.php
精彩评论