How can foreach loops be used to iterate through a JSON array in PHP?
To iterate through a JSON array in PHP using foreach loops, you need to first decode the JSON string into a PHP array using the json_decode() function. Once you have the array, you can then use a foreach loop to iterate through each element in the array.
$jsonString = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';
$array = json_decode($jsonString, true);
foreach ($array as $item) {
echo $item['name'] . ' is ' . $item['age'] . ' years old' . PHP_EOL;
}
Related Questions
- How can PHP be optimized to efficiently handle multiple database operations based on user actions?
- Are there any performance considerations when implementing row coloring in PHP-generated tables?
- What dependencies are required for the php_oci8.dll to work properly in PHP, especially on Windows platforms?