使用 PHP foreach 解析 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10758897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:58:36  来源:igfitidea点击:

Parsing JSON array with PHP foreach

phpforeachjson

提问by ToddN

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

想知道为什么我的 PHP 代码不会在 JSON 数据中显示“值”的所有“值”:

$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.

第一个 foreach 工作正常,但第二个会引发错误。

{
   "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"
            }, ...

回答by Jonas Osburg

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";
         }
    }        

回答by Jonathan M

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

您需要告诉它使用哪个索引data,或者双循环遍历所有索引。

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

例如,要获取外部数组中第 4 个索引中的值。:

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";
    }

}   

回答by Rocket Hazmat

$user->datais an array of objects. Each element in the array has a nameand valueproperty (as well as others).

$user->data是一个对象数组。数组中的每个元素都有一个nameandvalue属性(以及其他)。

Try putting the 2nd foreachinside the 1st.

尝试将第二个foreach放在第一个中。

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