Home > Backend Development > PHP Tutorial > How do I Loop Through JSON Arrays in PHP?

How do I Loop Through JSON Arrays in PHP?

DDD
Release: 2024-11-16 21:26:03
Original
317 people have browsed it

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>";
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template