0

I have a little problem, I'm in this situation: I have a json that I parse with no problems with json_decode making an object, in this array I have various values, in particular I have an array called "message" then I want to add values to this $jsonObj->message for example:

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

now I want to add another object to $jsonObj->message without removing other values then, what I want is:

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


$jsonObj->message ADD $json2;

So I should have $jsonObj->message->somethingIntoJson2 and $jsonObj->message->hello too;

Thank you.

2 Answers2

0

I fixed with What is the best method to merge two PHP objects?

0

You can use json_decode to with the true as the second parameter to convert it to an array then you can assign a new index and its value and then use 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"}}
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
  • Basically you suggest to modify everything as array and then convert to object? –  Jun 17 '19 at 11:55