У меня проблемы с массивом в структуру JSON в PHP для использования в Javascript - PullRequest
0 голосов
/ 07 апреля 2011


Я всегда борюсь с форматированием массива в JSON. Я использую плагин selectbox от TexoTela. Для плагина требуется структура json:

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

Мой php код:

    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.                              
    }  

Мой PHP-код возвращает {"4":"chickenpen 4"}

Вместо {"4":"chickenpen 4","5":"chickenpen 5", etc....}

Я думаю, это связано с кодом: $ location_list = array ($ value => $ text); Каждый раз, когда цикл foreach создает новый массив. Как мне отформатировать массив для вывода всех результатов в foreach вместо последнего результата?

-Rich

1 Ответ

5 голосов
/ 07 апреля 2011
    $location_list[$value] = $text;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...