Home > Article > Backend Development > How do I Loop Through JSON Arrays in PHP?
Looping Through JSON Arrays in PHP
A common task in web development involves working with data stored in JSON format. PHP provides a straightforward way to parse and iterate through JSON arrays.
JSON Decoding
The first step is to decode the raw JSON string into a PHP array using the json_decode() function. This function converts the JSON data into an array with PHP-compatible keys and values.
Looping Through the JSON Array
Once the JSON array has been decoded, you can loop through its elements using a regular PHP loop. The following example shows how to iterate over each object in the JSON array provided:
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]'; $arr = json_decode($json); foreach ($arr as $item) { echo "var1: " . $item->var1 . "<br>"; echo "var2: " . $item->var2 . "<br>"; echo "var3: " . $item->var3 . "<br><br>"; }
This loop will print the values of var1, var2, and var3 for each object in the JSON array. You can customize this loop to access and process the data as needed.
The above is the detailed content of How do I Loop Through JSON Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!