-1

I would like to get the values for 'datelog_collected' and 'value' fields:

{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }

So far, i tried with json_decode but without success. I want this to stay as an object. Thanks

Dim17300
  • 75
  • 5

3 Answers3

1

If you use

$object = json_decode($your_JSON_string);

datelog_collected and value will not be properties of the resulting $object.

The object will have only one property, data. data is a numerically indexed array (that is what the square brackets in the JSON mean) which contains one object. The properties you want belong to that object.

So you can get what you want with $object->data[0]->datelog_collected, etc.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

If you use json_decode as:

$res=json_decode('{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }');

$res would be an object so you can access: $res->data

And if you add second parameter true (json as array)

$res=json_decode('{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }', true);

$res would be an array so you can access: $res["data"]

F.Igor
  • 4,119
  • 1
  • 18
  • 26
  • I agree with your solution but how do i get the value of "value" for instance? $res->data->value? – Dim17300 Sep 01 '16 at 15:16
  • `$res`is an object but `$res->data`is an array with an object inside it. Hence you'll have to use `$res->data[0]->datelog_collected` to get the value store in `datelog_collected` – roberto06 Sep 01 '16 at 15:19
-3

Try this

<?php
$datelog_collected=array();
$datelog_value=array();
$data='{ "data": [ { "datelog_collected": "2016-09-01 13:57:13", "value": "36.06" } ] }';
$data_array=json_decode($data,true);//true create array if you want object then remove true
if(is_array($data_array)&&!empty($data_array))
{
    foreach ($data_array as $key => $value) {
    if(is_array($value))
    {       
        foreach ($value as $key1 => $value1) {
            foreach ($value1 as $key2 => $value2) {
            if($key2=="datelog_collected")
            {
                $datelog_collected[]=$value2;
            }else{
                $datelog_value[]=$value2;
            }
            }
        }
    }
    }

    //here is datelog_collected
    var_dump($datelog_collected);
    echo "<br/>-----------------------<br/>";
        //here is datelog_value
    var_dump($datelog_value);

}

?>

check working link http://main.xfiddle.com/7ffb488b/json_decoder.php

Abhijit Jagtap
  • 2,740
  • 2
  • 29
  • 43