【问题标题】:I am having issues with Array to JSON structure in PHP to be used in Javascript我在 Javascript 中使用 Array to JSON 结构时遇到问题
【发布时间】:2011-04-07 17:19:13
【问题描述】:


我总是在处理 Array 到 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", etc....}

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

-丰富

【问题讨论】:

    标签: php javascript arrays json


    【解决方案1】:
        $location_list[$value] = $text;
    

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 2021-08-04
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 2019-01-25
      相关资源
      最近更新 更多