如何循环遍历JSON数组

28

我该如何使用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 */

2
$json 不是一个 JSON 对象,而是一个字符串。 - Josh
1
+1 所以我应该先使用 json_decode($json) 吗? - Anthony
2
取消注释json_decode一行,然后只需循环遍历它返回的数组。(这与CodeIgniter无关) - Jonathan
$arr = json_decode($json, true); 这行代码的作用是将一个 JSON 格式的字符串转换为 PHP 数组。 - Anthony
1
实际上你的 JSON 字符串表示的是一个对象数组而不是单个对象。 - velop
2个回答

62

1) $json 是一个字符串,你需要先对它进行解码。

$json = json_decode($json);

2) 您需要循环遍历对象并获取其成员

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

}

6

另一个例子:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接