28

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
5
  • 2
    $json is not a json object its a string. Commented Apr 30, 2013 at 1:26
  • 1
    +1 so I should use json_decode($json) first? Commented Apr 30, 2013 at 1:27
  • 2
    Uncomment the line that says json_decode and just loop through the array that it returns. (and this has nothing to do with CodeIgniter) Commented Apr 30, 2013 at 1:27
  • +1 $arr = json_decode($json, true); ? Commented Apr 30, 2013 at 1:30
  • 1
    actually your json string represents an array of objects and not an object itself Commented Nov 6, 2017 at 15:30

2 Answers 2

62

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

6

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.