2013-04-30 3 views
13

Comment puis-je parcourir et afficher les noms dans le JSON suivant en utilisant CodeIgniter?Comment faire une boucle sur l'objet 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 $ n'est pas un objet JSON sa chaîne. – Josh

+1

+1 alors je devrais utiliser json_decode ($ json) en premier? – Anthony

+2

Décommentez la ligne qui indique json_decode et parcourez simplement le tableau qu'elle renvoie. (et ceci n'a rien à voir avec CodeIgniter) –

Répondre

32

1) $json est une chaîne que vous devez d'abord décoder.

$json = json_decode($json); 

2) vous devez faire une boucle à travers l'objet et obtenir ses membres

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

} 
+0

+1 Merci Josh pour l'explication. Je comprends maintenant. Ça a marché. – Anthony

2

un autre exemple:

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