dou448172583 2011-04-07 17:19
浏览 48
已采纳

我在PHP中使用Array to JSON结构的问题将在Javascript中使用


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

  • 写回答

1条回答 默认 最新

  • dongzhi4690 2011-04-07 17:25
    关注
        $location_list[$value] = $text;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题