Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Data from json to PHP array

I am having difficulty extracting data from a json response into an array using PHP. I can sucessfully get profile information. For example, part of the json response is: 

stdClass Object
(
    [user] => stdClass Object
        (
            [fullName] => Peter
            [topBadges] => Array
                (
                    [0] => stdClass Object
                        (
                            [badgeGradientEndColor] => A489E8
                            [badgeGradientStartColor] => 38216E
                            [badgeType] => DAILY_STEPS
                            [category] => Daily Steps

 And I can successfully name parts of this reponse as variables in PHP. For example, 

$name = $response->user->fullName;
$top_badge = $response->user->topBadges[0]->category;
$weight = $response->user->weight;

So, json data comes to me as an array and I can put it into variables. HOWEVER, I cannot do the same thing with time series data. For example, part of the json response is: 

stdClass Object
(
    [activities-steps] => Array
        (
            [0] => stdClass Object
                (
                    [dateTime] => 2015-03-05
                    [value] => 0
                )

            [1] => stdClass Object
                (
                    [dateTime] => 2015-03-06
                    [value] => 363
                )

 I do not know how to name these as variables. I want to have something like this:

$date0 = $response->{activities-steps}[0]->dateTime;
$steps0 = $response->{activities-steps}[0]->value; 
$date1 = $response->{activities-steps}[1]->dateTime;
$steps1 = $response->{activities-steps}[1]->value; 
etc.

 But the variables are blank. How do I get time series data into PHP variables?

Best Answer
0 Votes
2 REPLIES 2

I think what you want is to use http://php.net/json_decode with $assoc set to true

Best Answer
0 Votes

json_decode didn't work, but here's what did: I converted the response from an object to an array using this function: http://ageekandhisblog.com/php-how-to-convert-stdclass-object-to-array/ and then naming my variables like this:

$date0 = $response0['activities-steps'][0][dateTime];
$steps0 = $response0['activities-steps'][0][value]; 
$date1 = $response0['activities-steps'][1][dateTime];
$steps1 = $response0['activities-steps'][1][value]; 

 

Best Answer
0 Votes