简体   繁体   English

json用php中的数组解码

[英]json decode with an array in php

I am having a problem with getting data from json. 我在从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: 我的json看起来像这样:

{"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. 注释值是我可以从该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. 任何帮助,将不胜感激。

If this format is going to be always the same, you can use reset() function on this one. 如果此格式将始终相同,则可以在此格式上使用reset()函数。 Consider this example: 考虑以下示例:

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

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'];

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'];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM