【问题标题】:How to set attributes decoded json?如何设置属性解码的json?
【发布时间】:2017-01-12 07:48:21
【问题描述】:

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

  public function loadJson($id)
    {
        $jsonfile=ChForms::model()->findByPk($id);
        $decodedJson=json_decode($jsonfile->json, true);
        return $decodedJson;
    }

  public function actionForms($id){
               $forms = ChForms::model()->findByPk($id);
              if ($forms->name == 'plaint') {
                $plaint = new PlaintForm();
                $models = $plaint;
                $filesname=CJSON::decode($forms->json)["ABlock"]["p_1"];
                $plaint_type=CJSON::decode($forms->json)["CBlock"]["p_1"];
                var_dump($this->loadJson($id));
                $models->setAttributes($this->loadJson($id), false);
                var_dump($models);
                $doc = $models->toWord($models, $plaint_type);
                header("Content-Transfer-Encoding: binary");
                header("Content-Disposition: attachment; filename=$filesname.docx");
                header("Content-Length: " . filesize($doc));
                header("Pragma: public"); // required
                header("Expires: 0");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: private", false); // required for certain browsers
                //header("Content-Type:". $doc->mime_type);
                readfile($doc);
                unlink($doc);
                Yii::app()->end();
            }
        }

var_dump($this->loadJson($id)); 的结果是:

array(6) { ["ABlock"]=> array(36) { ["name"]=> string(6) "ablock" ["view"]=> string(10) "pdf/ablock" ["p_1"]=> string(12) "SSP 12345678"

结果

 $models->setAttributes($this->loadJson($id), false);
                var_dump($models);

object(PlaintForm)#84 (11) { ["ABlock"]=> object(ABlockForm)#85 (43) { ["name"]=> string(6) "ablock" ["view"]=> string(10) "pdf/ablock" ["p_1"]=> NULL

$models->setAttributes($this->loadJson($id), false); 

没有设置属性。我在哪里犯错了?如何设置属性?

【问题讨论】:

  • 方法setAttributes是做什么的?
  • 大量设置属性值

标签: php json yii yii1.x


【解决方案1】:

您可以使用以下 PHP 类将 JSON 映射到类。

https://github.com/cweiske/jsonmapper

$json     = json_decode(<JSON LOADED FROM ELSEWHERE>);
$mapper   = new JsonMapper();
$instance = $mapper->map($json, new <YOUR-CLASS>);

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2018-11-04
    • 2018-02-19
    相关资源
    最近更新 更多