【问题标题】:Passing JSON data from Controller to Model将 JSON 数据从 Controller 传递到 Model
【发布时间】:2015-06-30 10:12:47
【问题描述】:

我有以下 CodeIgniter 应用程序,我在其中尝试读取控制器中的外部 JSON 文件,并将其传递给我的模型函数 getKey(),最后,将从该函数返回的数据传递给我的视图。我不断收到错误消息“PHP Parse error: syntax error, unexpected '$this' (T_VARIABLE), expecting function (T_FUNCTION)”,我不确定是什么原因造成的。我是使用 CodeIgniter 的新手,因此感谢您提供任何帮助。

我的控制器:

class Test extends CI_Controller{
    public function __construct(){
        parent::__construct();
    }

    var $test_id = 1;
    var $json_key;
    $this->load->model('Test_model');

    $json_key = $this->test_model->getKey($test_id);
    $json_key = json_decode($json_key);
    $data['test_key'] = $json_key;

    $this->load->view('test_view', $data);
}

我的模特:

class Test_model extends CI_Model{
    var $image_array = array();
    var $test_key = array();
    var $test_name = '';

    public function __construct(){
        parent::__construct();
    }

    public function getKey($test_id){
        switch($test_id){
            case 1:
                $test_name = "sample1";
                break;
            case 2:
                $test_name = "sample2";
                break;
            case 3:
                $test_name = "sample3";
                break;
        }

        $image_array = file_get_contents('../files/' . $$test_name . '_key.json');
        $test_key = shuffle($image_array);

        return $image_array;
    }
}

我的看法:

<html>
  <head>
    <title>Test</title>
  </head>
  <body>
    <h1>Test Screen</h1>
    <?php print_r($test_key); ?>
    <?php print_r($json_key); ?>
  </body>
</html>

提前谢谢。

【问题讨论】:

    标签: php json codeigniter model-view-controller


    【解决方案1】:

    您的控制器错误。您的代码应该在一个函数中。像这样的:

    class Test extends CI_Controller
    {
      public function __construct()
      {
        parent::__construct();
      }
    
      function index()
      {
        $this->load->model('Test_model');
    
        $test_id = 1;
        $json_key = $this->test_model->getKey($test_id);
        $json_key = json_decode($json_key);
        $data['test_key'] = $json_key;
    
        $this->load->view('test_view', $data);
      }
    }
    

    【讨论】:

    • 这绝对是正确的,但是,在进行更改后,我仍然得到相同的错误,除了现在它不再指定 $this 变量,而是指向第 10 行的“var”。任何想法为什么?
    • var 不能在函数中。你可以离开var。这里不需要类成员变量。您可以只使用局部变量。我会更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2021-07-24
    • 2023-01-24
    相关资源
    最近更新 更多