How can nested foreach loops be effectively used to parse complex JSON structures in PHP?

Nested foreach loops can be used to effectively parse complex JSON structures in PHP by iterating through each level of the JSON data. By using nested loops, you can access nested arrays or objects within the JSON structure and extract the necessary information. This approach allows for flexibility in handling different levels of nesting within the JSON data.

$jsonData = '{
    "users": [
        {
            "id": 1,
            "name": "Alice",
            "pets": [
                {
                    "name": "Fluffy",
                    "type": "cat"
                },
                {
                    "name": "Spot",
                    "type": "dog"
                }
            ]
        },
        {
            "id": 2,
            "name": "Bob",
            "pets": [
                {
                    "name": "Bella",
                    "type": "cat"
                }
            ]
        }
    ]
}';

$data = json_decode($jsonData, true);

foreach ($data['users'] as $user) {
    echo "User: " . $user['name'] . "\n";
    
    foreach ($user['pets'] as $pet) {
        echo "Pet: " . $pet['name'] . " (" . $pet['type'] . ")\n";
    }
}