Vidyadhar Mandke
Vidyadhar Mandke

Reputation: 588

Something wrong in json parsing in php

I'm getting the following JSON response:

[
    {
        "startDate": "2012-07-12 11:21:38 +0530",
        "totalTime": 0
    },
    {
        "startDate": "2012-07-11 11:27:33 +0530",
        "totalTime": 0
    },
    {
        "startDate": "2012-07-16 18:38:37 +0530",
        "totalTime": 0
    },
    {
        "startDate": "2012-07-17 14:18:32 +0530",
        "totalTime": 0
    }
]

i want make array of startDate and totalTime, i have used these two lines but it wont work, please suggest..

    $obj  = json_decode($dateTimeArr); 
    $dateAr = $obj->{'startDate'}; 

Upvotes: 3

Views: 85

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99879

Your JSON string represents an Array or Objects. Each item of the array is an object like {"startDate":"2012-07-12 11:21:38 +0530","totalTime":0}.

So json_decode($dateTimeArr); returns the array. If you want to access to the first element you can use the $obj[0] syntax. Then to get the startDate property, use $obj[0]->startDate.

You can iterate over all array's items using foreach:

foreach ($obj as $item) {
    echo $item->startDate, "\n";
}

Upvotes: 5

Related Questions