我在extjs + yii框架中工作。我的客户端在extjs中,服务器端设计在yii框架中。所以extjs的形式输入通过json来到yii framewok。这个json在yii控制器动作中被接受为 -
public function actionSetUserAnswer()
{
$postData = json_decode(file_get_contents("php://input"), true);
$clientData = $postData['data'];
}
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中如何使用$ clientdata变量访问json的各个字段,如option,questionId等。
答案 0 :(得分:0)
您可以使用数组下标
$option = $clientData[0]['option']
或
$questionId = $clientData[0]['questionId']
如果要检索多个值以便在findByAttributes
中使用,则需要一组值。您首先从JSON中检索questionId
function get_question_id($elem) {
return $elem['questionId'];
}
$questionIds = array_map('get_question_id', $clientData);
然后在findByAttributes
$record=Question::model()->findByAttributes(array("questionId"=>$questionIds));
更新合并您的上一条评论:
static public function get_question_id($elem)
{
return $elem['questionId'];
}
public function actionSetUserAnswer() {
$clientData = '{"data":[{"optionId":"","questionId":"1","isAnswer":"","option":"Aus","media":"","keyword":"","mediaTypeId":"","id":null},...]}';
$obj = json_decode($clientData['data']);
$questionIds = array_map('get_question_id', $obj);
var_dump($questionIds);
$records = Question::model()->findByAttributes(array("questionId"=>$questionIds));
}