我有两个Object数组。数组1中的“ID”对应于数组2中的“media_id”,我需要将数组2的“album_ids”添加到数组1中。
对象1;
Array ( [0] => stdClass Object ( [ID] => 2482 [post_author] => 6 [post_date] => 2014-07-31 07:59:26) [1] => stdClass Object ( [ID] => 2483 [post_author] => 6 [post_date] => 2014-07-31 07:59:28)
对象2 =
Array ( [0] => stdClass Object ( [album_id] => 52 [media_id] => 2482 ) [1] => stdClass Object ( [album_id] => 92 [media_id] => 2483 )
我需要最终结果:
Array ( [0] => stdClass Object ( [ID] => 2482 [post_author] => 6 [post_date] => 2014-07-31 07:59:26 [album_id] => 52) [1] => stdClass Object ( [ID] => 2483 [post_author] => 6 [post_date] => 2014-07-31 07:59:28 [album_id] => 92)
感谢您的帮助!!
答案 0 :(得分:1)
根据您的问题,假设您有两个对象数组 - array1和array2。
aarry1 = Array([0] => stdClass对象([ID] => 2482 [post_author] => 6 [post_date] => 2014-07-31 07:59:26)[1] => stdClass对象([ID] => 2483 [post_author] => 6 [post_date] => 2014-07-31 07:59:28)
array2 = Array([0] => stdClass对象([album_id] => 52 [media_id] => 2482)[1] => stdClass对象([album_id] => 92 [media_id] => 2483)
现在试试这段代码。
$albumids = array();
foreach ( $array2 as $key => $val) {
$albumids[$val->media_id] = $val->album_id;
}
if(!empty($albumids)) {
foreach ( $array1 as $key => $val) {
if(isset($albumids[$val->ID])) {
$val->album_id = $albumids[$val->ID];
}
}
}
print_r($array1);
您将获得预期的结果
编辑:我必须更正以下行: $ val-> albumid = $ albumids [$ val-> id]; 至 $ val-> album_id = $ albumids [$ val-> ID];