1

If a JSON string has spaces in its name "Some Items" (is there a more accurate term for this?), how do you access it in PHP after using json_decode($json_string) on it? Is this name even required for data returned from an API?

JSON String

{"Some Items":[{"post_id":"1284"},{"post_id":"1392"},{"post_id":"1349"}]}

These doesn't work

$data = json_decode($json_string);
$data = $data->"Some Items";    // invalid PHP
$data = $data["Some Items"];    // Cannot use object of type stdClass as array
1

4 Answers 4

6

You need to use curly brace ($object->{'...'}) syntax:

$data->{'Some Items'}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this

$data->{'Some Items'};

Comments

2

Try that

<?php
$json = '{"Some Items":[{"post_id":"1284"},{"post_id":"1392"},{"post_id":"1349"}]}';
$decoded = json_decode($json);

// for example
echo($decoded->{"Some Items"}[0]->post_id);
?>

Comments

1

If you don't like the curly braces idea you can use the dynamic accessor business:

$someitems = "Some Items";
var_dump($data->$someitems);

Or, you could cast $data to an array and use the square brackets:

$data = (array)json_decode($json_str);
var_dump($data['Some Items']);

json_decode has a switch so you don't need to use casting.

$data = json_decode($json_str, true);
var_dump($data);

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.