Skip to content
Advertisement

Display JSON Response specific keys/values using PHP

I want to display specific keys and values from the following JSON Response I am using API to fetch the JSON values:

[
    {
        "tracking_data": {
            "track_status": 1,
            "shipment_status": 7,
            "shipment_track": [
                {
                    "id": 42719783,
                    "pickup_date": "2020-07-20 19:07:00",
                    "delivered_date": "2020-07-22 11:36:00",
                    "weight": "0.15",
                    "packages": 1,
                   
               }
            ],
          
            "shipment_track_activities": [
                {
                    "date": "2020-07-22 11:36:00",
                    "status": "DLVD",
                    "activity": "Delivered Shipment Delivered by SR: VasudevDengi, MobileNo: 7999869145, DeliveryDate: 2020-07-22 11:36:30, Receiver Name: Suman Rajnod ",
                    "location": "IDR/RJN, Indore, MADHYA PRADESH"
                },
                {
                    "date": "2020-07-22 10:21:00",
                    "status": "OFD",
                    "activity": "Out for Delivery Out for delivery: 104688-VasudevDengi-PDS20204102119104688-FromMob",
                    "location": "IDR/RJN, Indore, MADHYA PRADESH"
                },
                {
                    "date": "2020-07-22 08:09:00",
                    "status": "RAD",
                    "activity": "Reached at Destination InScan ( Shipment Auto Bagout )",
                    "location": "IDR/RJN, Indore, MADHYA PRADESH"
                },
                {
                    "date": "2020-07-21 07:07:00",
                    "status": "IT",
                    "activity": "InTransit Shipment added in ParentBagNo: NXBB024886",
                    "location": "IDR/IDR, Indore, MADHYA PRADESH"
                }
            ] 

I am trying to display with this php code but it’s giving blank screen, also the JSON values (I mentioned above) are assigned to $response variable.

$js = json_decode($response, true);

foreach($js as $return){
    
    echo $return['tracking_data']['track_status'];
} ?>

Addition – I can display track_status value following solution provided @Aashishgaba thanks, Can you also guide me to display data like “pickup_date” and “shipment_track_activities” as you can see there is multiple data based on dates.

Advertisement

Answer

$js = json_decode($response, true);

foreach($js as $return){    
    echo $return['tracking_data']['track_status'];
    foreach($return['tracking_data']['shipment_track'] as $st){
        echo $st['pickup_date'];
    }

    foreach($return['tracking_data']['shipment_track_activities'] as 
       $sta){
       echo $sta['date'];
       echo $sta['status'];
    }
} ?>

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement