1

I'm trying to access "note_id" in a JSON object.

php code

<?php

$test = 
'{"username":"Ellaleeeeeee",
  "event_source":"browser",
  "event":
  "{
     \"notes\": [{\"note_id\": \"2771\"}]
  }"
}';

$jarray = json_decode($test, true);
$jevent = json_decode($jarray['event'], true);

var_dump($jevent);

?>

I tried $jevent['notes']['note_id'][0] but failed.

Please kindly tell me what I am supposed to do. Thanks!

5
  • $jarray is already decoded, no need to decode it again in $jevent = .... $jevent = $jarray['event']; Commented May 20, 2019 at 7:26
  • 2
    @kerbholz Apparently the OP has another JSON string inside event which was initially a string. Commented May 20, 2019 at 7:27
  • 2
    @vivek_23 Yeah, realized this just now, thanks for pointing out Commented May 20, 2019 at 7:28
  • 1
    The order of your keys is incorrect. It should be $jevent['notes'][0]['note_id']. Commented May 20, 2019 at 7:28
  • it should be $jevent['notes'][0]['note_id'] not $jevent['notes']['note_id'][0] Commented May 20, 2019 at 7:52

1 Answer 1

3

You need to change code a bit like below:-

$jarray = json_decode($test, true);
$jevent = json_decode($jarray['event'], true);
echo $jevent['notes'][0]['note_id'];

Output:-https://3v4l.org/0sOfm

In case you want to get all note_id then use foreach()

<?php

$test = 
'{"username":"Ellaleeeeeee",
  "event_source":"browser",
  "event":
  "{\"notes\": [{\"note_id\": \"2771\"},{\"note_id\": \"2772\"}]}"
}';

$jarray = json_decode($test, true);
$jevent = json_decode($jarray['event'], true);

foreach($jevent['notes'] as $jnotes){

    echo $jnotes['note_id'].PHP_EOL;
}

Output:-https://3v4l.org/D7t0R

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I just edited the question because I wanna know whether indentation matters in this case. At the beginning, I formatted the code in that way and it didn't work out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.