1

I have two nested stdClass (multiple values).

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

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

I want to change a property of first object with some property of second. Both are stdClasses, tested with is_object. However I can't copy value to first object.

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

Where all are of type stdClass.

0

2 Answers 2

3

Your issue simply is that $object2 is not an object, since json_decode() fails. You had an issue with unbalanced quoting chars in the json string. Below is the fixed version which works fine:

<?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);

The output is:

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

)

A good idea in such case always is to read the error message raised with your code: "Trying to get property of non-object". That clearly points out what the issue is. Also some basic error handling never is a bad idea...

Sign up to request clarification or add additional context in comments.

Comments

0

Actually You can :) You have syntax error in "params:{"emailing": - it should be "params":{"emailing":

Try that:

$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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.