如何在 yii2 中将数组转换为 json
How to convert an array to json in yii2
我正在创建 restful apis
并且我有一个函数可以像这样 yii1
发送响应数据
public function sendResponse($data)
{
header('Content-Type: application/json; charset=utf-8');
echo CJSON::encode($data);
exit;
}
CJSON
在 Yii2
中不可用,所以我如何在 Yii2
中使用
无需像那样手动设置页眉。
在具体的动作/方法中可以这样设置:
use Yii;
use yii\web\Response;
...
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
}
然后 return 一个像这样的简单数组:
return ['param' => $value];
你可以在官方文档中找到这个 属性 here。
对于多个动作使用特殊的ContentNegotiator
过滤器是更灵活的方法:
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => ContentNegotiator::className(),
'only' => ['index', 'view']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
];
}
还有更多设置,可以在official docs中查看。
至于 REST,基础 yii\rest\Controller 已经为 json
和 xml
:
设置了它
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
::find()->asArray()->all();
希望得到帮助。
你可以在 yii2 中使用 Json class 来自
yii\helpers\Json;
它包含如下方法:
Json::encode();
Json::decode();
这些方法直接将yii2 activerecord对象转换成json数组。
我正在创建 restful apis
并且我有一个函数可以像这样 yii1
发送响应数据
public function sendResponse($data)
{
header('Content-Type: application/json; charset=utf-8');
echo CJSON::encode($data);
exit;
}
CJSON
在 Yii2
中不可用,所以我如何在 Yii2
无需像那样手动设置页眉。
在具体的动作/方法中可以这样设置:
use Yii;
use yii\web\Response;
...
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
}
然后 return 一个像这样的简单数组:
return ['param' => $value];
你可以在官方文档中找到这个 属性 here。
对于多个动作使用特殊的ContentNegotiator
过滤器是更灵活的方法:
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => ContentNegotiator::className(),
'only' => ['index', 'view']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
];
}
还有更多设置,可以在official docs中查看。
至于 REST,基础 yii\rest\Controller 已经为 json
和 xml
:
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
::find()->asArray()->all(); 希望得到帮助。
你可以在 yii2 中使用 Json class 来自
yii\helpers\Json;
它包含如下方法:
Json::encode();
Json::decode();
这些方法直接将yii2 activerecord对象转换成json数组。