Anthony Anthony - 1 month ago 6
JSON Question

How do I loop through JSON object

How do I traverse and display the names in the following JSON using CodeIgniter?

<?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 */

Answer

1) $json is a string you need to decode it first.

$json = json_decode($json);

2) you need to loop through the object and get its members

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

}
Comments