普通网友 2015-02-20 14:08
浏览 37
已采纳

带有Json问题的PHP数组

I want to achieve this using my php script:

{  
    "aaData":[  
        [  
            "100",
            "189",
            "2"
        ],
        [  
            "100",
            "189",
            "1"
        ],
        [  
            "100",
            "188",
            "4"
        ],
        [  
            "100",
            "188",
            "3"
        ],
        [  
            "100",
            "188",
            "2"
        ]
    ]
}

I am fetching data from database, and i want to put results to above format. Query looks like this:

SELECT user_id, module_id, action_id FROM test;

Please help me to put results of these 3 columns on format which i mentioned above.

Regards

  • 写回答

1条回答 默认 最新

  • dongmei1988 2015-02-20 14:14
    关注

    Using PDO, you can do:

    $result = $conn->execute("SELECT `user_id`, `module_id`, `action_id` FROM `test`");
    $rows = $result->fetchAll(PDO::FETCH_NUM);
    echo json_encode(array('aaData' => $rows));
    

    fetchAll returns a 2-dimensional array of the results of the query. The PDO::FETCH_NUM mode makes the rows of these results be numerically-indexed arrays. Then we put this into the aaData element of another array, and convert it to JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符