YII 把yii多层对象转成数组和统一json返回值
if (is_array($models))
$arrayMode = TRUE;
else {
$models = array($models);
$arrayMode = FALSE;
}
$result = array();
foreach ($models as $model) {
$attributes = $model->getAttributes();
if (isset($filterAttributes) && is_array($filterAttributes)) {
foreach ($filterAttributes as $key => $value) {
if (strtolower($key) == strtolower($model->tableName()) && strpos($value, ‘*‘) === FALSE) {
$value = str_replace(‘ ‘, ‘‘, $value);
$arrColumn = explode(",", $value);
foreach ($attributes as $key => $value)
if (!in_array($key, $arrColumn))
unset($attributes[$key]);
}
}
}
$relations = array();
foreach ($model->relations() as $key => $related) {
if ($model->hasRelated($key)) {
if(($model->$key instanceof CModel) || is_array($model->$key)){
$relations[$key] = self::convertModelToArray($model->$key, $filterAttributes);
} else {
$relations[$key] = $model->$key;
}
}
}
$all = array_merge($attributes, $relations);
if ($arrayMode)
array_push($result, $all);
else
$result = $all;
}
return $result;
}
$this->_sendResponse(array(‘errorCode‘=>int,‘errorMessage‘=>‘‘,‘data‘=>array());
public function _sendResponse($attr = array(), $ct=self::CONTENT_TYPE_JSON) {
if ($ct === self::CONTENT_TYPE_JSON){
header("Content-type:application/json");
} else {
header("Content-type:text/plain");
}
$response = array();
$response[‘errorCode‘] = isset($attr[‘errorCode‘])? $attr[‘errorCode‘] : ApiError::ERROR_OK;
$response[‘errorMessage‘] = empty($attr[‘errorMessage‘])? ApiError::getErrorMessage($response[‘errorCode‘]) : $attr[‘errorMessage‘];
$response[‘data‘] = empty($attr[‘data‘]) ? null : $attr[‘data‘];
echo CJSON::encode($response);
Yii::app()->end();
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。