1

I have a json file and I want to display it data using PHP. My below code gives me error,

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);
$users = $data['devices'];
foreach($users as $user)
{
echo $user['id'];
echo $user['user'];
}

When I replace the 3rd LOC with $users = $data['user']; then it display some data with single alphabet i don't know in which order.

Data.json file contains the following data

{
"user":
    {
    "id":"#03B7F72C1A522631",
    "user":"[email protected]",
    "password":"123",
    "email":"[email protected]",
    "name":"m",
    "creationDate":1385048478,
    "compression":true,
    "imageProfile":"medium",
    "videoProfile":"medium",
    "blockAdvert":true,
    "blockTracking":true,
    "devices":[
        {
        "id":"#13C73379A7CC2310",
        "udid":"cGMtd2luNi4xLV",
        "user":"[email protected]",
        "creationDate":1385048478,
        "status":"active",
        }, 
        {
        "id":"#FE729556EDD9910D",
        "udid":"C1N1",
        "user":"[email protected]",
        "creationDate":1385291938,
        "status":"active",
        }]
    },
"status":
    {
    "version":"0.9.5.0",
    "command":"getuser",
    "opf":"json",
    "error":false,
    "code":0
    }
}

4 Answers 4

4

I believe you skipped 1 node, try:

$users = $data['user']['devices'];
Sign up to request clarification or add additional context in comments.

Comments

4

This should work;

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);
$users = $data['user']['devices'];
foreach($users as $user) {
    echo $user['id'];
    echo $user['user'];
}

There is one key before 'devices'.

Comments

3

I think you may want do display all the devices info, you can change you code to:

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);

// change the variable name to devices which is clearer.
$devices = $data['user']['devices'];
foreach ($devices as $device)
{
    echo $device['id'];
    echo $device['user'];
}

Comments

1

You are not accessing your json correctly. You need to access it like this.

$yourVariable = $data['users']['devices'];

Try that.

4 Comments

OP wrote $data = json_decode($json,true); which returns an array instead of object.
docs.php.net/json_decode the documentation says that if the parameter $assoc is true it will turn objects into associative arrays. I am pretty sure this is false by default correct me if I am wrong.
phpriot.com/manual/php/function.json-decode this example shows an object is returned by default if the $assoc parameter is left out.
It defaults to false, but OP explicit wrote true

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.