【问题标题】:How to update value of stdClass with another stdClass nested property in PHP如何使用 PHP 中的另一个 stdClass 嵌套属性更新 stdClass 的值
【发布时间】:2015-07-19 08:22:48
【问题描述】:

我有两个嵌套的 stdClass(多个值)。

$object1 = json_decode ('{"key":"value", "emailing":{"live":false, "test":true}}')

$object2 = json_decode ('{"key":"value", "params:{"emailing":{"live":false, "test":true}, "esp":"email"}}')

我想用第二个属性更改第一个对象的属性。两者都是标准类,用 is_object 测试。 但是我无法将值复制到第一个对象。

$object1->emailing = $object2->params->emailing;

所有的都是stdClass类型。

【问题讨论】:

    标签: php stdclass


    【解决方案1】:

    您的问题只是 $object2 不是对象,因为 json_decode() 失败。您在 json 字符串中遇到了不平衡引用字符的问题。以下是可以正常工作的固定版本:

    <?php    
    $object1 = json_decode ('{"key":"value", "emailing":{"live":false, "test":true}}');
    $object2 = json_decode ('{"key":"value", "params":{"emailing":{"live":false, "test":true}, "esp":"email"}}');
    
    $object1->emailing = $object2->params->emailing;
    print_r($object1);
    

    输出是:

    stdClass Object
    (
        [key] => value
        [emailing] => stdClass Object
            (
                [live] =>
                [test] => 1
            )
    
    )
    

    在这种情况下,一个好主意始终是阅读代码引发的错误消息:“尝试获取非对象的属性”。这清楚地指出了问题所在。此外,一些基本的错误处理绝不是一个坏主意......

    【讨论】:

      【解决方案2】:

      其实你可以:) "params:{"emailing": 有语法错误 - 应该是 "params":{"emailing":

      试试看:

      $object1 = json_decode('{"key":"value", "emailing":{"live":false, "test":true}}');
      $object2 = json_decode('{"key":"value", "params":{"emailing":{"live":"newvalue1", "test":"newvalue2"}, "esp":"email"}}');
      
      // before
      print_r($object1);
      
      // after
      $object1->emailing = $object2->params->emailing;
      print_r($object1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-27
        • 2019-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多