如何使用php从json数组中提取数据?

时间:2022-07-08 16:00:42

I am trying to extract the full_name value from the below json. I have been able to extract from the "query" section using this code.

我试图从下面的json中提取full_name值。我已经能够使用此代码从“查询”部分中提取。

echo $data->query->params->granularity;

This prints out neighbourhood.

这个打印。

But I am unable to echo the full_name. Im guessing this is because I have to do something different because of the [] but I'm new to this and not at sure what to do.

但是我不能重复full_name。我猜这是因为我必须做一些不同的事情,因为[]但我是新手,不知道该怎么做。

None of these seem to work.

这些似乎都不奏效。

foreach ($data['places'] as $item) { ough!
echo $item->result->places->contained_within->attributes->full_name;
echo $item->result->places->full_name;
echo $item->result->full_name;
echo $item->full_name;  
}

Any help would be greatly appreciated.

如有任何帮助,我们将不胜感激。

{
  "query": {
    "params": {
      "accuracy": 0,
      "coordinates": {
        "coordinates": [
          -122.42284884,
          37.76893497
        ],
        "type": "Point"
      },
      "granularity": "neighborhood"
    },
    "type": "reverse_geocode"
  },
  "result": {
    "places": [
      {
        "attributes": {

        },
        "bounding_box": {
          "coordinates": [
            [
              [
                -122.42676492,
                37.75983003
              ],
              [
                -122.420736,
                37.75983003
              ],
              [
                -122.420736,
                37.77226299
              ],
              [
                -122.42676492,
                37.77226299
              ]
            ]
          ],
          "type": "Polygon"
        },
        "contained_within": [
          {
            "attributes": {

            },
            "bounding_box": {
              "coordinates": [
                [
                  [
                    -122.51368188,
                    37.70813196
                  ],
                  [
                    -122.35845384,
                    37.70813196
                  ],
                  [
                    -122.35845384,
                    37.83245301
                  ],
                  [
                    -122.51368188,
                    37.83245301
                  ]
                ]
              ],
              "type": "Polygon"
            },
            "country": "United States",
            "country_code": "US",
            "full_name": "San Francisco, CA",
            "id": "5a110d312052166f",
            "name": "San Francisco",
            "place_type": "city"
          }
        ],
        "country": "United States",
        "country_code": "US",
        "full_name": "Mission Dolores, San Francisco",
        "id": "cf7afb4ee6011bca",
        "name": "Mission Dolores",
        "place_type": "neighborhood"
      }
    ]
  }
}

5 个解决方案

#1


1  

First problem the json is not valid. There are few issue. You can validate at following website: http://jsonlint.com/

第一个问题,json无效。很少有问题。您可以在以下网站验证:http://jsonlint.com/

And the json have two full name. So following code will help to extract those two full names.

json有两个全称。下面的代码将帮助提取这两个完整的名称。

$json = 'Assign the json here';
$json_array = json_decode($json);
echo $json_array->result->places[0]->contained_within[0]->full_name;
echo $json_array->result->places[0]->full_name;
  • Assign the valid json to the variable $json within single quot (') as json have double quot.
  • 将有效的json分配给单“(')”内的变量$json,因为json有双“。

The tested code available here: http://sugunan.net/demo/json1.php

这里提供的测试代码:http://sugunan.net/demo/json1.php

If we take your foreach example it need to be modified like follows. But that is not tested answer.

如果我们以你的foreach示例为例,它需要如下所示进行修改。但这还没有经过检验的答案。

foreach ($data['places'] as $item) {
echo $item->contained_within[0]->full_name;
echo $item->full_name;
}

Following is the validated json of the above. Which had few unnecessary ",". And it missed few brackets.

下面是上述的验证json。这几乎没有必要。它漏掉了几个括号。

{
"query": {
    "params": {
        "accuracy": 0,
        "coordinates": {
            "coordinates": [
                -122.42284884,
                37.76893497
            ],
            "type": "Point"
        },
        "granularity": "neighborhood"
    },
    "type": "reverse_geocode"
},
"result": {
    "places": [
        {
            "attributes": {},
            "bounding_box": {
                "coordinates": [
                    [
                        [
                            -122.42676492,
                            37.75983003
                        ],
                        [
                            -122.420736,
                            37.75983003
                        ],
                        [
                            -122.420736,
                            37.77226299
                        ],
                        [
                            -122.42676492,
                            37.77226299
                        ]
                    ]
                ],
                "type": "Polygon"
            },
            "contained_within": [
                {
                    "attributes": {},
                    "bounding_box": {
                        "coordinates": [
                            [
                                [
                                    -122.51368188,
                                    37.70813196
                                ],
                                [
                                    -122.35845384,
                                    37.70813196
                                ],
                                [
                                    -122.35845384,
                                    37.83245301
                                ],
                                [
                                    -122.51368188,
                                    37.83245301
                                ]
                            ]
                        ],
                        "type": "Polygon"
                    },
                    "country": "United States",
                    "country_code": "US",
                    "full_name": "San Francisco, CA",
                    "id": "5a110d312052166f",
                    "name": "San Francisco",
                    "place_type": "city"
                }
            ],
            "country": "United States",
            "country_code": "US",
            "full_name": "Mission Dolores, San Francisco",
            "id": "cf7afb4ee6011bca",
            "name": "Mission Dolores",
            "place_type": "neighborhood"
        }
    ]
}

}

}

#2


0  

After I had fixed your JSON (probably copy-paste errors) I have accessed the first (lowest branch) full_name by using:

修正了JSON(可能是复制粘贴错误)之后,我使用以下方法访问了第一个(最低的分支)full_name:

$data = json_decode($json);
foreach($data->result->places as $item) {
  echo $item->name; // Mission Dolores, San Francisco
}

And the second element named full_name by using:

第二个元素full_name:

$data = json_decode($json);
foreach($data->result->places as $item) {
  foreach($item->contained_within as $cont) {
    echo $cont->full_name; // San Francisco, CA
  }
}

The philosophy behind parsing JSON is that some elements have one set of named element for a level, and the other has a number of recurring sets of elements. In this case there is a element called result -> places which can be more than one. And in there there is an element called contained_within which has more elements of its own. The correct way is looping over them using for/foreach but they can also be directly adressed:

解析JSON背后的原理是,有些元素为一个级别拥有一组已命名的元素,而另一个元素则拥有一系列重复出现的元素。在这种情况下,有一个名为result ->位置的元素,它可以大于1。其中有一个名为contained_within的元素,其中包含了更多自己的元素。正确的方法是使用for/foreach对它们进行循环,但也可以直接添加:

$data = json_decode($json);
echo $data->result->places[0]->full_name; // Mission Dolores, San Francisco
echo $data->result->places[0]->contained_within[0]->full_name; // San Francisco, CA

#3


0  

You need to decode your json first then do a foreach...you can try this

您需要先解码您的json,然后做一个foreach…你可以试试这个

$json = json_decode("YOUR JSON HERE");
foreach ($json->result->places as $place) {
    echo $place->full_name;
}

#4


0  

A quick guide to accessing items within a decoded JSON data structure:

在解码的JSON数据结构中访问项目的快速指南:

Run your json through a validator/formatter so you can see the structure. I use this formatter as you can open and close the nodes to see the structure easily.

通过验证器/格式化程序运行json,以便查看结构。我使用这个格式化程序,因为您可以打开和关闭节点,以方便地查看结构。

When you do json_decode($json_string), PHP's json decoder creates objects and (non-associative) arrays. To access data in objects, use the syntax $object->Attribute. To access data in arrays, give the index of the array item: $array[0] for the first item, $array[1] for the second item, etc.

当您执行json_decode($json_string)时,PHP的json解码器创建对象和(非关联)数组。要访问对象中的数据,请使用语法$object->属性。要访问数组中的数据,请给出数组项的索引:第一个项为$array[0],第二个项为$array[1],等等。

Examples:

例子:

$data = json_decode($json);
echo "accuracy: " . $data->query->params->accuracy . "\n";
// output: "accuracy: 0"
echo "coord 1: " . $data->query->params->coordinates->coordinates[0] . "\n";
// output: "coord 1: -122.42284884"

foreach ($data->query->params->coordinates->coordinates as $c)
    echo "coord: " . $c . "\n"
// output: 
// coord: -122.42284884
// coord: 37.76893497

To get items deeper in the data structure, chain together these accessors. For example, to get full_name, you would use the following:

要在数据结构中获得更深入的项,请将这些访问器链接在一起。例如,要获取full_name,可以使用以下命令:

echo "Full name: " . $data->result->places[0]->full_name . "\n";
// output: Full name: Mission Dolores, San Francisco

#5


0  

Since you are looping from "places" already, the full_name property would be in $item->full_name already.

由于您已经在“places”中循环,full_name属性将在$item->full_name中。

Same goes for the contained_within struct, $item->contained_within->full_name should work.

对于struct中的contained_within, $item->contained_within->full_name应该可以使用。

#1


1  

First problem the json is not valid. There are few issue. You can validate at following website: http://jsonlint.com/

第一个问题,json无效。很少有问题。您可以在以下网站验证:http://jsonlint.com/

And the json have two full name. So following code will help to extract those two full names.

json有两个全称。下面的代码将帮助提取这两个完整的名称。

$json = 'Assign the json here';
$json_array = json_decode($json);
echo $json_array->result->places[0]->contained_within[0]->full_name;
echo $json_array->result->places[0]->full_name;
  • Assign the valid json to the variable $json within single quot (') as json have double quot.
  • 将有效的json分配给单“(')”内的变量$json,因为json有双“。

The tested code available here: http://sugunan.net/demo/json1.php

这里提供的测试代码:http://sugunan.net/demo/json1.php

If we take your foreach example it need to be modified like follows. But that is not tested answer.

如果我们以你的foreach示例为例,它需要如下所示进行修改。但这还没有经过检验的答案。

foreach ($data['places'] as $item) {
echo $item->contained_within[0]->full_name;
echo $item->full_name;
}

Following is the validated json of the above. Which had few unnecessary ",". And it missed few brackets.

下面是上述的验证json。这几乎没有必要。它漏掉了几个括号。

{
"query": {
    "params": {
        "accuracy": 0,
        "coordinates": {
            "coordinates": [
                -122.42284884,
                37.76893497
            ],
            "type": "Point"
        },
        "granularity": "neighborhood"
    },
    "type": "reverse_geocode"
},
"result": {
    "places": [
        {
            "attributes": {},
            "bounding_box": {
                "coordinates": [
                    [
                        [
                            -122.42676492,
                            37.75983003
                        ],
                        [
                            -122.420736,
                            37.75983003
                        ],
                        [
                            -122.420736,
                            37.77226299
                        ],
                        [
                            -122.42676492,
                            37.77226299
                        ]
                    ]
                ],
                "type": "Polygon"
            },
            "contained_within": [
                {
                    "attributes": {},
                    "bounding_box": {
                        "coordinates": [
                            [
                                [
                                    -122.51368188,
                                    37.70813196
                                ],
                                [
                                    -122.35845384,
                                    37.70813196
                                ],
                                [
                                    -122.35845384,
                                    37.83245301
                                ],
                                [
                                    -122.51368188,
                                    37.83245301
                                ]
                            ]
                        ],
                        "type": "Polygon"
                    },
                    "country": "United States",
                    "country_code": "US",
                    "full_name": "San Francisco, CA",
                    "id": "5a110d312052166f",
                    "name": "San Francisco",
                    "place_type": "city"
                }
            ],
            "country": "United States",
            "country_code": "US",
            "full_name": "Mission Dolores, San Francisco",
            "id": "cf7afb4ee6011bca",
            "name": "Mission Dolores",
            "place_type": "neighborhood"
        }
    ]
}

}

}

#2


0  

After I had fixed your JSON (probably copy-paste errors) I have accessed the first (lowest branch) full_name by using:

修正了JSON(可能是复制粘贴错误)之后,我使用以下方法访问了第一个(最低的分支)full_name:

$data = json_decode($json);
foreach($data->result->places as $item) {
  echo $item->name; // Mission Dolores, San Francisco
}

And the second element named full_name by using:

第二个元素full_name:

$data = json_decode($json);
foreach($data->result->places as $item) {
  foreach($item->contained_within as $cont) {
    echo $cont->full_name; // San Francisco, CA
  }
}

The philosophy behind parsing JSON is that some elements have one set of named element for a level, and the other has a number of recurring sets of elements. In this case there is a element called result -> places which can be more than one. And in there there is an element called contained_within which has more elements of its own. The correct way is looping over them using for/foreach but they can also be directly adressed:

解析JSON背后的原理是,有些元素为一个级别拥有一组已命名的元素,而另一个元素则拥有一系列重复出现的元素。在这种情况下,有一个名为result ->位置的元素,它可以大于1。其中有一个名为contained_within的元素,其中包含了更多自己的元素。正确的方法是使用for/foreach对它们进行循环,但也可以直接添加:

$data = json_decode($json);
echo $data->result->places[0]->full_name; // Mission Dolores, San Francisco
echo $data->result->places[0]->contained_within[0]->full_name; // San Francisco, CA

#3


0  

You need to decode your json first then do a foreach...you can try this

您需要先解码您的json,然后做一个foreach…你可以试试这个

$json = json_decode("YOUR JSON HERE");
foreach ($json->result->places as $place) {
    echo $place->full_name;
}

#4


0  

A quick guide to accessing items within a decoded JSON data structure:

在解码的JSON数据结构中访问项目的快速指南:

Run your json through a validator/formatter so you can see the structure. I use this formatter as you can open and close the nodes to see the structure easily.

通过验证器/格式化程序运行json,以便查看结构。我使用这个格式化程序,因为您可以打开和关闭节点,以方便地查看结构。

When you do json_decode($json_string), PHP's json decoder creates objects and (non-associative) arrays. To access data in objects, use the syntax $object->Attribute. To access data in arrays, give the index of the array item: $array[0] for the first item, $array[1] for the second item, etc.

当您执行json_decode($json_string)时,PHP的json解码器创建对象和(非关联)数组。要访问对象中的数据,请使用语法$object->属性。要访问数组中的数据,请给出数组项的索引:第一个项为$array[0],第二个项为$array[1],等等。

Examples:

例子:

$data = json_decode($json);
echo "accuracy: " . $data->query->params->accuracy . "\n";
// output: "accuracy: 0"
echo "coord 1: " . $data->query->params->coordinates->coordinates[0] . "\n";
// output: "coord 1: -122.42284884"

foreach ($data->query->params->coordinates->coordinates as $c)
    echo "coord: " . $c . "\n"
// output: 
// coord: -122.42284884
// coord: 37.76893497

To get items deeper in the data structure, chain together these accessors. For example, to get full_name, you would use the following:

要在数据结构中获得更深入的项,请将这些访问器链接在一起。例如,要获取full_name,可以使用以下命令:

echo "Full name: " . $data->result->places[0]->full_name . "\n";
// output: Full name: Mission Dolores, San Francisco

#5


0  

Since you are looping from "places" already, the full_name property would be in $item->full_name already.

由于您已经在“places”中循环,full_name属性将在$item->full_name中。

Same goes for the contained_within struct, $item->contained_within->full_name should work.

对于struct中的contained_within, $item->contained_within->full_name应该可以使用。