php - 在 yii 中查询后返回 JSON

标签 php json rest yii

我是 yii 框架的新手。我只是想实现 Restful API。在简单的案例场景中(在遵循一些教程之后)我已经成功了:

$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;

另一部分(嵌套循环)似乎是用关系编码(see here)那么我的问题是什么是用关系编码,什么时候有用?

最佳答案

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();

关于php - 在 yii 中查询后返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798805/

相关文章:

php - GROUP BY table1.column_name ORDER BY table2.column_name

仅使用 WEB API key 的 Firebase Cloud Firestore REST api 身份验证?

java - 将 UUID 与 RESTful URL 标准结合使用的最佳实践是什么 :/collection/{Id}?

java - json解析函数返回奇怪的包名

javascript - jQuery 无法正确解析 JSON

javascript - Angular - 将 Jackson 输出转换为 JSON

php - WordPress 博客标题 url

php - 无法使用 Laravel 连接到本地 MySQL 服务器

php - 如何不使用脚本语言而使用 jquery 进行搜索?

c# - 无法将当前json数组反序列化为类型