2013-03-18 287 views
13

我使用返回我给定一个数组像这样的电子邮件地址的API:合并两个对象在PHP

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 
       ) 

     ) 

) 

如何合并信息[联系方式]与[名单] [0]中的单个对象?

谢谢您的帮助

+0

[你有什么尝试?](http:// whathaveyoutried .com) – starshine531 2013-03-18 09:23:31

回答

19
$info = yourstuff; 
$arrContact = (array) $info->contact; 
$arrList = (array) $info->lists[0]; 
$merged = array_merge($arrContact, $arrList); 
var_dump($merged, 'have fun'); 

并不重要;)

+0

这是非常好的:) – 2013-03-18 09:58:47

+0

问题的更好的解决方案 – Basith 2014-11-12 06:58:21

9
<?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" 
    } 
*/ 
+1

我喜欢将它再次投射到对象的想法。太糟糕了,我以前没有想到。 – Joshua 2013-03-18 10:06:22

+0

不能使用stdClass类型的对象作为数组 – 2014-09-26 13:45:47

+0

这应该是公认的答案! – patrick 2015-01-15 23:42:46

2

如何:

foreach ($info->lists[0] as $key => $value { 
    $info->contact->$key = $value; 
} 

避免了铸造来回阵列之间和对象