0

var_dump($response);

outputs:

 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }

how can I convert $response to an object to operate it like in the following code:

echo $response->metafields[0]->id;

I've tried the code below, but without any result :/

$object = json_decode(json_encode($response));
2
  • Your approach looks good but $response->metafields[0] doesn't exist. Try $response->metafields[13]. Commented Mar 31, 2017 at 11:16
  • 2
    why .... just (object) $array; Commented Mar 31, 2017 at 11:16

3 Answers 3

3

If you want to access your "metafields's id" like $response->metafields[13][id] then you need to cast your response array to object.

Ex.

$response = (object) array(
    'metafields' => array(
            '13' => (object) array(
                    'id' => 32616923206,
                    'namespace' => "ly26638"
                )
        )
);

Then you can use syntax like $response->metafields[13]->id to access the "id" value.

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

Comments

1

If you make an object with (object) $response, the child elements will still be arrays. Then you could do

$response->metafields[13][id]

If you want the object notation through the whole chain you need something like the function sandip has provided.

But why not just make this call:

$response[metafields][13][id]

3 Comments

ok, but how I can access only the second metafield ? every metafield has got index of 13 now, cause previously they were filtered.
That must be the second parameter in the response array. Try $response[1]['metafields'][13]['id']. Change the first parameter accordingly.
I've looped all the values from Array to my XML: foreach ($response->metafields as $meta) { echo "<designation><![CDATA[".$meta->value."]]></designation>"; } it solved my problem, thanks for your help ! :)
0

You can't find the member of an object by '[]'.

The '[]' is for arrays, and the '->' is for objects.

So the reason for the blank output is: metafields[0].

The code below is wrong:

echo $response->metafields[0]->id;

So you should change the key of the array, the key of an array should not be a pure number.

I tried to change the key to 'a13', and with the code of:

echo $response->metafields->a13->id;

I got "32616923206".

That's all. O(∩_∩)O~

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.