【问题标题】:How do I loop through JSON array如何循环遍历 JSON 数组
【发布时间】:2013-04-30 01:25:35
【问题描述】:

如何使用 CodeIgniter 遍历并显示以下 JSON 中的名称?

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Search extends CI_Controller {
    public function index()
    {       

        $json = '[{"name": "John Doe",
                 "address": "115 Dell Avenue, Somewhere",
                 "tel": "999-3000",
                 "occupation" : "Clerk"},
                 {"name": "Jane Doe",
                 "address": "19 Some Road, Somecity",
                 "tel": "332-3449",
                 "occupation": "Student"}]';


        for (int $i = 0; $i < $json.length; $i++){
            ???
        }
        //$obj = json_decode($json);        
        //$this->load->view('search_page');
    }
}

/* End of file search.php */
/* Location: ./application/controllers/search.php */

【问题讨论】:

  • $json 不是一个 json 对象,它是一个字符串。
  • +1 所以我应该先使用 json_decode($json)?
  • 取消注释 json_decode 的行,然后循环遍历它返回的数组。 (这与CodeIgniter无关)
  • +1 $arr = json_decode($json, true); ?
  • 实际上你的json字符串代表一个对象数组而不是一个对象本身

标签: php json codeigniter


【解决方案1】:

1) $json 是你需要先解码的字符串。

$json = json_decode($json);

2) 你需要遍历对象并获取它的成员

foreach($json as $obj){
   echo $obj->name;
   .....

}

【讨论】:

    【解决方案2】:

    另一个例子:

      <?php
    
      //lets make up some data:
      $udata['user'] = "mitch";
      $udata['date'] = "2006-10-19";
      $udata['accnt'] = "EDGERS";
      $udata['data'] = $udata; //array inside
      var_dump($udata); //show what we made
    
      //lets put that in a file
      $json = file_get_contents('file.json');
      $data = json_decode($json);
      $data[] = $udata;
      file_put_contents('file.json', json_encode($data));
    
      //lets get our json data
      $json = file_get_contents('file.json');
      $data = json_decode($json);
      foreach ($data as $obj) {
            var_dump($obj->user);
      }
    

    【讨论】:

      猜你喜欢
      • 2021-04-26
      • 2013-02-12
      • 2023-03-07
      • 2015-07-22
      • 2013-08-16
      • 2011-06-11
      • 2013-02-06
      • 1970-01-01
      相关资源
      最近更新 更多