Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.


I always struggle with Array to JSON formatting. I am using a selectbox plugin from TexoTela. The plugin requires a json structure as:

{
    "ajax1": "AJAX option 1",
    "ajax2": "AJAX option 2",
    "ajax3": "AJAX option 3"
}  

My php code:

    function get_selectfield_list($col, $table)
    {
        $location_list = array();

        //create an sql string and set it to the $sql variable
        $sql = "SELECT id, $col FROM $table";

        //form the sql query and set it to the $query variable
        $query = $this->db->query($sql);

        //loop through the result_array and set the results to the $location_list array
        foreach ($query->result_array() as $row)
        {
            $value = $row['id']; //set the database table id to to $value variable
            $text = $row[$col]; //set the the $string value to the $text variable
            $location_list = array($value => $text); //form the $location_list array with the the $value and $text values
        }

        echo json_encode($location_list); //convert the $location_list array into a json object and return it.                              
    }  

My PHP code returns {"4":"chickenpen 4"}

Instead of {"4":"chickenpen 4","5":"chickenpen 5", etc....}

I think that is due to the code: $location_list = array($value => $text); Every time the foreach loops it creates a new array. How do I format the array to output all the results in the foreach instead of the last result?

-Rich

share|improve this question

1 Answer 1

up vote 5 down vote accepted
    $location_list[$value] = $text;
share|improve this answer
    
That was simple. I have to read up about Arrays. –  dottedquad Apr 7 '11 at 17:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.