如何在 yii 1 中解码 json

How to decode json in yii 1

我的控制器中有以下代码:

public function actionCabinet($id){

    $this->render('cabinet', array('model'=>$this->loadJson($id)) );

}

    public function loadJson($id)
    {

        $jsonfile=ChForms::model()->findByPk($id, array("select"=>"json"));
        $decodedJson=json_decode($jsonfile, true);
        return $decodedJson;

    }

数据以json格式保存在ChForm的json字段中。我要把它转换成数组。当我 运行 这个应用程序时,它显示以下错误消息:

json_decode() expects parameter 1 to be string, object given

如何解决这个错误?

您可以像下面那样使用json_encode,

public function loadJson($id)
{

    $jsonfile=ChForms::model()->findByPk($id, array("select"=>"json"));
    $decodedJson=json_encode($jsonfile, true);
    return $decodedJson;

}

请试试这个,

 public function loadJson($id)
{

    $jsonfile=ChForms::model()->findByPk($id);
    $decodedJson=json_decode($jsonfile->json, true);
    return $decodedJson;

}