-2

Here is the string: [{"cid":"PWER","data":[{"1567613277000":10541}],"sid":"780160","units":"W","age":5},{"cid":"PWER_SUB","data":[{"1567613272000":384}],"sid":"780630","units":"W","age":10}] I can't get the value our for Data

I have tried looping through the array with no luck

$arr = json_decode($j,true);
    echo $arr[0][0];

Just returns an error

I am trying to get 1567613277000":10541 as the result.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Dean
  • 1
  • 2
    Because the inner arrays are an associative array, not a numerical array. Have you done `var_dump($arr);`? – aynber Sep 04 '19 at 16:49
  • Be useful to share the error message. – ficuscr Sep 04 '19 at 16:50
  • You must try this echo $arr[0]['data'][0]['1567613277000']; as it's an associative array. – ShubhamD Sep 04 '19 at 16:52
  • The last number changes all the time , I am trying to write its result to a Database every minute, I m not sure how to read into an associative array, if I use $arr[0][0] it says Notice: Undefined offset: 0 in /opt/lampp/htdocs/index.php on line 9 – Dean Sep 04 '19 at 16:54
  • I also get Notice: Undefined offset: 5 in /opt/lampp/htdocs/index.php on line 12 everytime I try different ways of access the array echo "

    "; echo $arr[5]["data"]; echo "

    "; echo $arr[4]['data'];
    – Dean Sep 04 '19 at 17:05
  • 1
    I'd suggest using [`array_key_first()`](https://www.php.net/manual/en/function.array-key-first.php) to find out the first key in the `data` array, then you can access the value that way. – aynber Sep 04 '19 at 17:23

1 Answers1

0

I'll share functional code with you since you are struggling. This question has really been answered in the comments though. Encourage you to also vote it a duplicate question and close it up.

<?php
$json = '[{
    "cid": "PWER",
    "data": [{
        "1567613277000": 10541
    }],
    "sid": "780160",
    "units": "W",
    "age": 5
}, {
    "cid": "PWER_SUB",
    "data": [{
        "1567613272000": 384
    }],
    "sid": "780630",
    "units": "W",
    "age": 10
}]';

$a = json_decode($json, true);

foreach ($a as $k => $v) {
  $foo = $v['data'][0];
  $fooKey = key($foo);
  $fooValue = reset($foo);

  var_dump('key:' . $fooKey, 'value:' . $fooValue);
}

Remember var_dump is your friend. It's just an array that looks complicated because of the nesting. Iterate and dump, step by step, you can manage any array no matter how complex.

ficuscr
  • 6,975
  • 2
  • 32
  • 52