Как мне выполнить цикл через объект JSON


Как мне просмотреть и отобразить имена в следующем JSON с помощью 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 */
Author: Anthony, 2013-04-30

2 answers

1) $json это строка, которую вам нужно сначала расшифровать.

$json = json_decode($json);

2) вам нужно пройти по объекту и получить его элементы

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

}
 37
Author: Josh, 2013-04-30 01:31:48

Другой пример:

  <?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);
  }
 2
Author: Mike Q, 2016-10-17 23:11:20