Home > Backend Development > PHP Tutorial > How do I traverse a JSON array in PHP?

How do I traverse a JSON array in PHP?

Mary-Kate Olsen
Release: 2024-11-16 05:24:03
Original
722 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template