• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
need help formating JSON

#1
[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

#2
[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 ;
                                        
        }

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

-Rich


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.