2013-04-30 138 views
13

如何使用CodeIgniter遍歷並顯示以下JSON中的名稱?如何通過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是不是一個JSON對象的字符串。 – Josh 2013-04-30 01:26:47

+1

+1所以我應該先使用json_decode($ json)? – Anthony 2013-04-30 01:27:40

+2

取消註釋表示json_decode的行並僅循環返回的數組。 (這與CodeIgniter無關) – 2013-04-30 01:27:57

回答

32

1)$json是需要先解碼的字符串。

$json = json_decode($json); 

2)你通過對象需要循環,並得到其成員

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

} 
+0

+1謝謝喬希的解釋。我現在知道了。有效。 – Anthony 2013-04-30 01:38:03

2

另一個例子:

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