25

Wondering why my PHP code will not display all "Value" of "Values" in the JSON data:

$user = json_decode(file_get_contents($analytics));
foreach($user->data as $mydata)
{
     echo $mydata->name . "\n";

}        
foreach($user->data->values as $values)
{
     echo $values->value . "\n";
}

The first foreach works fine, but the second throws an error.

{
   "data": [
      {
         "id": "MY_ID/insights/page_views_login_unique/day",
         "name": "page_views_login_unique",
         "period": "day",
         "values": [
            {
               "value": 1,
               "end_time": "2012-05-01T07:00:00+0000"
            },
            {
               "value": 6,
               "end_time": "2012-05-02T07:00:00+0000"
            },
            {
               "value": 5,
               "end_time": "2012-05-03T07:00:00+0000"
            }, ...
3
  • What's the error? Tell us what the output is. Commented May 25, 2012 at 17:32
  • Is $user->data an array? Because you go trough it with foreach. Commented May 25, 2012 at 17:33
  • 1
    Error is:Warning: Invalid argument supplied for foreach(). $user->data appears to be an array of [0]; Commented May 25, 2012 at 17:34

3 Answers 3

55

You maybe wanted to do the following:

foreach($user->data as $mydata)

    {
         echo $mydata->name . "\n";
         foreach($mydata->values as $values)
         {
              echo $values->value . "\n";
         }
    }        
Sign up to request clarification or add additional context in comments.

Comments

9

You need to tell it which index in data to use, or double loop through all.

E.g., to get the values in the 4th index in the outside array.:

foreach($user->data[3]->values as $values)
{
     echo $values->value . "\n";
}

To go through all:

foreach($user->data as $mydata)
{
    foreach($mydata->values as $values) {
        echo $values->value . "\n";
    }

}   

Comments

5

$user->data is an array of objects. Each element in the array has a name and value property (as well as others).

Try putting the 2nd foreach inside the 1st.

foreach($user->data as $mydata)
{
    echo $mydata->name . "\n";
    foreach($mydata->values as $values)
    {
        echo $values->value . "\n";
    }
}

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.