"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do I Loop Through JSON Arrays in PHP?

How do I Loop Through JSON Arrays in PHP?

Published on 2024-11-19
Browse:586

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 . "
"; echo "var2: " . $item->var2 . "
"; echo "var3: " . $item->var3 . "

"; }

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3