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 */
Jimbo Jonny
3,5791 gold badge21 silver badges23 bronze badges
asked Apr 30, 2013 at 1:25
-
2$json is not a json object its a string.Josh– Josh2013年04月30日 01:26:47 +00:00Commented Apr 30, 2013 at 1:26
-
1+1 so I should use json_decode($json) first?Anthony– Anthony2013年04月30日 01:27:40 +00:00Commented Apr 30, 2013 at 1:27
-
2Uncomment the line that says json_decode and just loop through the array that it returns. (and this has nothing to do with CodeIgniter)Jonathan– Jonathan2013年04月30日 01:27:57 +00:00Commented Apr 30, 2013 at 1:27
-
+1 $arr = json_decode($json, true); ?Anthony– Anthony2013年04月30日 01:30:39 +00:00Commented Apr 30, 2013 at 1:30
-
1actually your json string represents an array of objects and not an object itselfvelop– velop2017年11月06日 15:30:10 +00:00Commented Nov 6, 2017 at 15:30
2 Answers 2
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;
.....
}
answered Apr 30, 2013 at 1:31
Comments
another example:
<?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);
}
answered Oct 17, 2016 at 23:11
Comments
lang-php