php - 我在将 PHP 中的数组转为 JSON 结构用于 Javascript 时遇到问题

标签 php javascript arrays json


我总是在数组到 JSON 格式方面遇到困难。我正在使用 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"等...}

我认为这是由于代码: $location_list = array($value => $text);每次 foreach 循环都会创建一个新数组。如何格式化数组以输出 foreach 中的所有结果而不是最后一个结果?

-丰富

最佳答案

    $location_list[$value] = $text;

关于php - 我在将 PHP 中的数组转为 JSON 结构用于 Javascript 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5584997/

相关文章:

php - GIF 到 mp4 转换

javascript - 当音频包含在另一个PHP文件中时,音频不起作用

javascript - 如果 Javascript 中不存在某个项目,则跳过而不出现错误

javascript - 页面加载后加载 Google Chrome 扩展脚本

javascript - amChart 列文本自动旋转

php - 仅将唯一值插入数组

php - 如何知道点击了哪个按钮?

php - 如何检查页面变慢的原因?

arrays - 带数组的 Groovy 简单函数

c - 在指针上调试 C 程序时出错