将 JSON 数据从控制器传递到模型

Passing JSON data from Controller to Model

我有以下 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>

提前致谢。

你的控制器有问题。您的代码应该在一个函数中。像这样:

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);
  }
}