从控制器传递JSON以在Codeigniter中查看 [英] Passing JSON from controller to view in codeigniter

查看:75
本文介绍了从控制器传递JSON以在Codeigniter中查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了API调用,并接收了JSON格式的响应。

I made an API call and received the response in JSON format.

JSON:

JSON:

{
  "Specialities": [
    {
      "SpecialityID": 1,
      "SpecialityName": "Eye Doctor"
    },
    {
      "SpecialityID": 2,
      "SpecialityName": "Chiropractor"
    },
    {
      "SpecialityID": 3,
      "SpecialityName": "Primary Care Doctor"
    }
  ]
}

控制器文件:

public function index(){
      $data= json_decode(file_get_contents('some_url'));
      $this->load->view('my_view',$data);
}

上面的代码不起作用,因为在视图中我无法访问嵌套对象的属性。但是我可以像这样在控制器文件中回显JSON属性:

Above code doesn't work because in view I can't access the nested object properties. However I am able to echo the JSON properties in controller file just like this:

控制器文件:

Controller File:

public function index(){

     $data=json_decode(file_get_contents('some_url'));
     foreach ($data as $key=>$prop_name){
        for($i=0;$i < count($prop_name);$i++){
          echo $prop_name[$i]->SpecialityID;
          echo $prop_name[$i]->SpecialityName;
        }
     }
}

我的问题是如何将此JSON传递给视图以及如何访问视图文件中的那些属性?

My question is how do I pass this JSON to view and how can I access those properties in view file?

推荐答案

按照文档


数据通过视图加载方法第二个参数中的数组
对象从控制器传递到视图。

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method.

以下是使用数组的示例:

因此您需要在以下位置更改代码控制器

So you need to change your code in controller

Controller.php

$data = array();
$data['myJson'] = json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);

my_view.php

<html>
....
<?php 
//Access them like so
print_r($myJson);
// Rest of your code here to play with json 
?>
....
</html>

这篇关于从控制器传递JSON以在Codeigniter中查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆