1

我在 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 字段。所以有人可以帮我吗

4

1 回答 1

1

您必须使用 解码 json CJSON::decode,然后访问以下字段:

$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比依赖 native 更好json_decode,因为当 native 不可用时,CJSON::decode 仍然可以解码 json 字符串。同样在某些情况下json_decode可以返回null正确的 json 字符串,请阅读此处以比较 php json 库。

于 2013-01-30T07:24:59.937 回答