我在extjs + yii工作。我的服务器端设计在yii框架中,客户端设计在extjs中。现在从extjs我得到json格式的输出数据=
{"data":[{"optionId":"","questionId":"1","isAnswer":"","option":"Aus","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"2","isAnswer":"","option":"india","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"3","isAnswer":"","option":"England","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"4","isAnswer":"","option":"Srilanka","media":"","keyword":"","mediaTypeId":"","id":null}]}
所以在Yii frameowk中如何访问这个json字段?我想访问这个json的questionId和optionId字段。那么请有人帮助我
答案 0 :(得分:1)
您必须使用CJSON::decode
解码json,然后访问字段:
$var='{"data":[{"optionId":"","questionId":"1","isAnswer":"","option":"Aus","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"2","isAnswer":"","option":"india","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"3","isAnswer":"","option":"England","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"4","isAnswer":"","option":"Srilanka","media":"","keyword":"","mediaTypeId":"","id":null}]}';
$decoded=CJSON::decode($var);
// now your json is stored in $decoded as an array, so you can access as follows:
echo $decoded["data"][0]["questionId"];
echo $decoded["data"][0]["optionId"];
// to loop over the elements use foreach
foreach ($decoded["data"] as $value){
echo $value["questionId"];
echo $value["optionId"];
}
使用CJSON::decode
比依赖本地json_decode
要好,因为当本机不可用时,CJSON :: decode仍然可以解码json字符串。 Also in some cases json_decode
can return null
for correct json strings,阅读here以了解php json库的比较。