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 */
Looping Using JSON JSON stands for JavaScript Object Notation. It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values.
Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.
1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.
The Basic For LoopJavaScript arrays are zero based, which means the first item is referenced with an index of 0. As you can see the for loop statement uses three expressions: the initialization, the condition, and the final expression. The final expression is executed at the end of each loop execution.
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; ..... }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With