php 在php中合并两个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15473194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:18:32 来源:igfitidea点击:
Merge two objects in php
提问by Christophe Martin
I use an API that returns me to an email address given an array like this:
我使用一个 API 返回给我一个电子邮件地址给定这样的数组:
stdClass Object
(
[status] => OK
[contact] => stdClass Object
(
[id] => 0000000
[email] => [email protected]
[last_activity] => 1362131446
[last_update] => 0
[created_at] => 1356617740
[sent] => 5
[open] => 1
[click] => 1
[spam] => 0
[bounce] => 0
[blocked] => 0
[queued] => 0
)
[lists] => Array
(
[0] => stdClass Object
(
[active] => 1
[unsub] => 1
[unsub_at] => 1363078528
)
)
)
how to merge info [contact] with [lists] [0] in a single object?
如何在单个对象中将信息 [contact] 与 [lists] [0] 合并?
Thank you for your help
感谢您的帮助
回答by Joshua
$info = yourstuff;
$arrContact = (array) $info->contact;
$arrList = (array) $info->lists[0];
$merged = array_merge($arrContact, $arrList);
var_dump($merged, 'have fun');
Quite trivial ;)
相当微不足道;)
回答by Gaurang
<?php
$a = new stdClass;
$a->name = 'Anthony';
$b = new stdClass;
$b->location = 'UK';
$c = (object)array_merge((array)$a, (array)$b);
var_dump($c);
/*
object(stdClass)#3 (2) {
["name"]=>
string(7) "Anthony"
["location"]=>
string(2) "UK"
}
*/
回答by Colin Shipton
How about:
怎么样:
foreach ($info->lists[0] as $key => $value {
$info->contact->$key = $value;
}
Avoids casting back and forth between arrays and objects
避免在数组和对象之间来回转换

