0

I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:

{"102":{"textinput":{"comment":"2"}},"104":"34"}
 OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}

Comment value is my serialnumber that I net to get from this json. I tried with :

$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];

But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.

asked Jun 12, 2014 at 8:27
4
  • Why not use array_keys to get the keys and maybe array_shift on the result to get the first one? Commented Jun 12, 2014 at 8:30
  • are you just after the comment index? Commented Jun 12, 2014 at 8:32
  • you can simply use foreach. It would give the result. Commented Jun 12, 2014 at 8:32
  • yes, i need just the comment Commented Jun 12, 2014 at 8:32

3 Answers 3

2

If this format is going to be always the same, you can use reset() function on this one. Consider this example:

$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
answered Jun 12, 2014 at 8:33
Sign up to request clarification or add additional context in comments.

2 Comments

what in case when it is not the same?
@enigmaticus assuming the json structure stays the same, reset() will just take that first element, so you dont hav the need to manually put the key since it will always change.
1

How about:

$snr_array = array()
foreach ($json_sn as $key)
 snr_array[] = $key['textinput']['comment'];

Edit: I just realized that you might just need/get one comment:

$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
answered Jun 12, 2014 at 8:32

Comments

0

You can do:

<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
 # Check if exsit
 if (isset($value['textinput']['comment'])) {
 echo "Value: " . $value['textinput']['comment'];
 }
}
answered Jun 12, 2014 at 8:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.