【问题标题】:Add an object to an existing variable into the object [duplicate]将对象添加到对象中的现有变量中[重复]
【发布时间】:2019-06-16 22:33:45
【问题描述】:

我有一个小问题,我处于这种情况:我有一个我解析的 json,而 json_decode 创建一个对象没有问题,在这个数组中我有各种值,特别是我有一个名为“消息”的数组然后我想向这个$jsonObj->message 添加值,例如:

$jsonObj->message->hello = 'example';

现在我想在不删除其他值的情况下向$jsonObj->message 添加另一个对象,我想要的是:

$jsonObj->message->hello; // this is auto generated from the json


$jsonObj->message ADD $json2;

所以我也应该有$jsonObj->message->somethingIntoJson2$jsonObj->message->hello

谢谢。

【问题讨论】:

    标签: php arrays json object variables


    【解决方案1】:

    您可以使用json_decodetrue 作为第二个参数将其转换为数组,然后您可以分配一个新索引及其值,然后使用json_encode

    $jsonArr = [
    'mesage' => [
        'hello' => 'example'
     ]
    ];
    $j   = json_encode($jsonArr);
    echo $j;//{"mesage":{"hello":"example"}}
    $obj = json_decode($j,true);
    $obj['mesage']['element'] = 'value';
    echo json_encode($obj);//{"mesage":{"hello":"example","element":"value"}}
    

    【讨论】:

    • 基本上你建议将所有内容修改为数组,然后转换为对象?
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2020-07-13
    • 2012-05-08
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 2021-09-06
    • 2021-11-12
    相关资源
    最近更新 更多