Texan78
Texan78

Reputation: 687

How to parse JSON data from nested array in PHP

I am struggling to retrieve some values from a JSON file formatted like this:

{
"@context": [
    "https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld",
    {
        "wx": "https://api.weather.gov/ontology#",
        "@vocab": "https://api.weather.gov/ontology#"
    }
],
"type": "FeatureCollection",
"features": [
    {
        "id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
        "type": "Feature",
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [
                        -95.45,
                        32.36
                    ],
                    [
                        -96.07,
                        32.36
                    ],
                    [
                        -96.08,
                        32.76
                    ],
                    [
                        -95.92,
                        32.82
                    ],
                    [
                        -95.85,
                        32.77
                    ],
                    [
                        -95.77,
                        32.77
                    ],
                    [
                        -95.76,
                        32.75
                    ],
                    [
                        -95.71,
                        32.75
                    ],
                    [
                        -95.66,
                        32.71
                    ],
                    [
                        -95.64,
                        32.72
                    ],
                    [
                        -95.59,
                        32.68
                    ],
                    [
                        -95.6,
                        32.48
                    ],
                    [
                        -95.47,
                        32.37
                    ],
                    [
                        -95.45,
                        32.36
                    ]
                ]
            ]
        },
        "properties": {
            "@id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
            "@type": "wx:Alert",
            "id": "NWS-IDP-PROD-2485131-2320093",
            "areaDesc": "Van Zandt",
            "geocode": {
                "UGC": [
                    "TXC467"
                ],
                "SAME": [
                    "048467"
                ]
            },
            "references": [],
            "sent": "2017-08-13T00:03:41+00:00",
            "effective": "2017-08-13T00:03:41+00:00",
            "onset": "2017-08-13T00:03:00+00:00",
            "expires": "2017-08-13T01:00:00+00:00",
            "ends": "2017-08-13T01:00:00+00:00",
            "status": "Actual",
            "messageType": "Alert",
            "category": "Met",
            "severity": "Severe",
            "certainty": "Observed",
            "urgency": "Immediate",
            "event": "Severe Thunderstorm Warning",
            "sender": "NWS Fort Worth TX",
            "headline": "Severe Thunderstorm Warning issued August 12 at 7:03PM CDT expiring August 12 at 8:00PM CDT by NWS Fort Worth TX",
            "description": "The National Weather Service in Fort Worth has issued a\n\n* Severe Thunderstorm Warning for...\nVan Zandt County in north central Texas...\n\n* Until 800 PM CDT.\n\n* At 703 PM CDT, a severe thunderstorm was located near Wills Point,\nmoving east at 25 mph.\n\nHAZARD...65 mph wind gusts and quarter size hail.\n\nSOURCE...Radar indicated.\n\nIMPACT...Hail damage to vehicles is expected. Expect wind damage\nto roofs, siding, and trees.\n\n* This severe thunderstorm will be near,\nCanton around 710 PM CDT.\nEdgewood around 715 PM CDT.\nFruitvale around 725 PM CDT.\nGrand Saline around 735 PM CDT.\nVan around 750 PM CDT.\n\nThis includes Interstate 20 between mile markers 513 and 542.",
            "instruction": "For your protection get inside a sturdy structure and stay away from\nwindows.\n\nContinuous cloud to ground lightning is occurring with this storm.\nMove indoors immediately. Lightning can kill.\n\nHeavy rainfall is occurring with this storm, and may lead to flash\nflooding. Do not drive your vehicle through flooded roadways.",
            "response": "Shelter",
            "parameters": {
                "eventMotionDescription": [
                    "2017-08-13T00:03:00.000-05:00...storm...277DEG...23KT...32.62,-95.97"
                ],
                "hailSize": [
                    "1.00"
                ],
                "windGust": [
                    65
                ],
                "tornadoDetection": [
                    "POSSIBLE"
                ],
                "VTEC": [
                    "/O.NEW.KFWD.SV.W.0313.170813T0003Z-170813T0100Z/"
                ],
                "EAS-ORG": [
                    "WXR"
                ],
                "PIL": [
                    "FWDSVRFWD"
                ],
                "BLOCKCHANNEL": [
                    "CMAS",
                    "EAS",
                    "NWEM"
                ],
                "eventEndingTime": [
                    "2017-08-13T01:00:00Z"
                ]
            }
        }
    },

I am trying to get the values from the keys under the "properties" key. What I am struggling with is does the array start with "properties" nested under @context or under "features"? I am not familiar with JSON data that uses @ keys.

There are more values I need. But for starters, I am just using the event key nested under "features" -> "properties" where most of the keys for the values I need. I am not getting output from that.

    <?php

$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($data, true); // decode the JSON feed


foreach($results as $result) {
    dump($result); //this will dump the array
    foreach($results['features'] as $data) {
        dump($data['event']);
    }
}

?>

-Thanks

EDIT: Added suggestion to code for json_decode

Upvotes: 1

Views: 2756

Answers (3)

Rob Ruchte
Rob Ruchte

Reputation: 3707

As others have stated, you need to pass true as a second param to json_decode if you want to the result to be an associative array.

The hierarchy is features/properties/event so you can look through the features and pull what you want out of the properties of each feature.

<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$results = json_decode($data, true); // decode the JSON feed

foreach($results['features'] as $currFeature)
{
    $currEvent = $currFeature['properties']['event'];
    echo $currEvent."\n";
}

Upvotes: 1

Bamse
Bamse

Reputation: 493

As BarNakedCoder said: json_decode($data, true) but you also need to replace

dump($data['event']

with:

dump($data[0]['event'])

Upvotes: 0

CodeBoy
CodeBoy

Reputation: 3300

Use json_decode($data, true). The true tells json_decode to return nested associative arrays instead of a object.

Upvotes: 0

Related Questions