小编典典

如何遍历JSON数组

json

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

阅读 298

收藏
2020-07-27

共1个答案

小编典典

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

$json = json_decode($json);

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

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

}
2020-07-27