In the previous article "Two methods for deleting key values in associative arrays in PHP", I introduced how to delete key values in associative arrays. Friends in need can read and learn~
The focus of this article is to teach you how to traverse json data.
I wonder how much everyone knows about json? JSON is actually a lightweight data exchange format; JSON is also a sequence of markers, which contains six construction characters, strings, numbers and three literal names; JSON is also a serialized object or array . (Related recommendations: "What is a JSON file" "What does json mean? What is it used for?")
After a brief understanding of json, we will Directly upload the code:
PHP method of traversing json data:
Note: This example requires looping through 10924 10923 11982 and the corresponding id title and other values.
<?php $str = '{ "10924": { "id": "10924", "title": "天津", "streamline_title": "狗不理", "unit": "点", "goods_type": "168", "goods_type_title": "包子" }, "10923": { "id": "10923", "title": "北京", "streamline_title": "王府井", "unit": "点", "goods_type": "104", "goods_type_title": "吃货天堂" }, "11982": { "id": "11982", "title": "南京", "streamline_title": "夫子庙", "unit": "点", "goods_type": "351", "goods_type_title": "灯会" } }'; foreach (json_decode($str) as $v) { echo "{$v->id} {$v->title}"; //其他的一样的 }
Output result:
10924 天津 10923 北京 11982 南京
Here is a json_decode
function:
json_decode is a new one after php5.2.0 PHP's built-in function is used to encode strings in JSON format. So how to use this function?
The syntax rules of json_decode:
json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
json_decode accepts a JSON format string and converts it into a PHP variable. When the parameter $assoc is TRUE, array will be returned, otherwise object will be returned. .
JSON format string
$json = '{"a":"php","b":"mysql","c":3}';
where a is the key, and php is the key value of a.
PHP Chinese website platform has a lot of video teaching resources. Welcome everyone to learn "PHP Video Tutorial"!
The above is the detailed content of How to traverse json data in php program. For more information, please follow other related articles on the PHP Chinese website!