CodeIgniter Forums
need help formating JSON - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: need help formating JSON (/showthread.php?tid=32789)



need help formating JSON - El Forum - 08-04-2010

[eluser]dottedquad[/eluser]
Hello all,
My current code:

Code:
function get_location_list()
        {
            $location_list = array();
            
            $query = $this->db->query('SELECT id, location FROM location');
            
            foreach ($query->result_array() as $row)
            {
                $value = $row['id'];
                $text = $row['location'];
                
                $location_list['result'][$value] = $text;    
            }
            echo json_encode($location_list);
            
            //return ;
                                        
        }
My JSON is formatted as such:
{"result":{"1":"chickenpen 1","2":"chickenpen 2","3":"chickenpen 3","4":"chickenpen 4"}}

It should be formatted like:
Code:
{"results":[  
     {"id":1,"name":"chickenpen 1"},  
     {"id":2,"name":"chickenpen 2"},  
     {...} // more results here...  
]}

How do I get my JSON string to be formatted like the above sample?

-Thank You,
Rich


need help formating JSON - El Forum - 08-04-2010

[eluser]bretticus[/eluser]
Your json code shows each result as an associative array within a larger array. Just format accordingly:

Code:
function get_location_list()
        {
            $location_list = array('results' => array());
            
            $query = $this->db->query('SELECT id, location FROM location');
            
            foreach ($query->result_array() as $row)
            {
                $value = $row['id'];
                $text = $row['location'];
                $location_list['results'][] = array('id' => $value, 'name' => $text);
            }
            echo json_encode($location_list);
            
            //return ;
                                        
        }



need help formating JSON - El Forum - 08-04-2010

[eluser]dottedquad[/eluser]
Your code works as expected. Thank you. Now to read up on arrays.

-Rich