Php 在yii中查询后返回JSON
我是yii框架的新手。我只是想实现Restful API。在简单案例场景中(在完成一些教程之后),我成功地做到了以下几点:Php 在yii中查询后返回JSON,php,json,rest,yii,Php,Json,Rest,Yii,我是yii框架的新手。我只是想实现Restful API。在简单案例场景中(在完成一些教程之后),我成功地做到了以下几点: $result = []; foreach($this->getData() as $record) { $result[] = $record->getAttributes(); } return $result; 请注意,getData()是一个内置方法。其中,当尝试使用查询进行更高级的场景时,是这样做的: $attributeNames = 'u
$result = [];
foreach($this->getData() as $record) {
$result[] = $record->getAttributes();
}
return $result;
请注意,getData()
是一个内置方法。其中,当尝试使用查询进行更高级的场景时,是这样做的:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
$attributeNames = explode(',', $attributeNames);
$rows = array();
foreach ($models as $model) {
$row = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$rows[] = $row;
}
return $rows;
这是从查询结果返回get JSON的最佳实践,还是可以用更好的方法
更新:
通过以下方法返回最终响应:
private function sendAjaxResponse(AjaxResponseInterface $interface)
{
$success = count($interface->getErrors()) === 0;
$responseCode = $success ? 200 : 404;
header("content-type: application/json", true, $responseCode);
echo json_encode([
'success' => $success,
'data' => $interface -> getResponseData(),
'errors' => $interface -> getErrors()
]);
Yii::app()->end();
}
我发现只有这些线是足够的:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
return $models;
另一部分(嵌套循环)似乎是用关系编码的(),那么我的问题是什么是用关系编码,什么时候有用?我认为您只需要在返回之前对值进行编码
foreach ($models as $model) {
$row = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$rows[] = $row;
}
return json_encode($rows);
Yii创建JSOn数据的方法是使用CJson库
$query = "'select ' . $attributeNames . ' from device'";
$command = Yii::app()->db->createCommand($query);
$result = $command->queryAll();
$ret = array_values($result);
/* or ...
$ret = array();
foreach ($models as $model) {
$ret = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$ret[] = $row;
}
*/
echo CJSON::encode($ret);
Yii::app()->end();
非常简单只需添加这一行-\Yii::$app->response->format=\Yii\web\response::format\u JSON开始时在方法中使用code>并执行其他代码
通常
例如
public function actionHospitals()
{
\Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;
$hospitals = Hospitals::find()->select('speciality')->distinct()->all();
return ['hospitals' => $hospitals];
}
谢谢@scaisEdge,它确实被编码了,请看我的更新。如果我的回答有帮助,请给它打分