[英]json decode with an array in php
我在從json獲取數據時遇到問題。 我無法更改它在數據庫中的保存方式,因為它是由框架生成的,並且在讀取之后用於字段生成。 我的json看起來像這樣:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
注釋值是我可以從該json獲得的序列號。 我嘗試了:
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
但這不是我需要的解決方案,因為我不知道第一個數字鍵的值,因此我不能依靠它。 任何幫助,將不勝感激。
如果此格式將始終相同,則可以在此格式上使用reset()
函數。 考慮以下示例:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
怎么樣:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
編輯:我剛剛意識到您可能只需要/獲得一條評論:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
你可以做:
<?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.