Home > Article > Backend Development > How do I traverse a JSON array in PHP?
JSON Array Traversal in PHP
Working with JSON data is essential in web development. A common task is iterating through JSON arrays to access and manipulate their elements. In PHP, you can achieve this using the json_decode() function.
To illustrate, consider the following JSON array:
[ { "var1": "9", "var2": "16", "var3": "16" }, { "var1": "8", "var2": "15", "var3": "15" } ]
To loop through this array, you can follow these steps:
$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]'); foreach($arr as $item) { $uses = $item['var1']; //etc }
The json_decode() function converts the JSON string into a PHP array, which can then be iterated through using a regular loop. Within the loop, you can access the individual elements of each object in the array using the object key as an index, as demonstrated in the example above.
The above is the detailed content of How do I traverse a JSON array in PHP?. For more information, please follow other related articles on the PHP Chinese website!