Parsing JSON array with PHP foreach

后端 未结 3 731
广开言路
广开言路 2020-11-29 04:09

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-&g         


        
相关标签:
3条回答
  • 2020-11-29 04:46

    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";
        }
    
    }   
    
    0 讨论(0)
  • 2020-11-29 04:46

    $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";
        }
    }
    
    0 讨论(0)
  • 2020-11-29 04:49

    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";
             }
        }        
    
    0 讨论(0)
提交回复
热议问题