douji0108 2015-03-23 14:16
浏览 45
已采纳

如何使用php [关闭]在json中返回一个mysql select作为数组数组

I am trying to export a mysql request (select) to a json array of array, so that JSON.parse in javascript will return an array of arrays and not an array of objects as what will happen following answers to similar questions previously asked.

What should be changed to translate a mysql request into a json array of array?

  • 写回答

1条回答 默认 最新

  • du4822 2015-03-23 14:16
    关注

    For json_encode to return a JSON array of array you need a numerically indexed array.

    This can be obtained with the following, generic function:

        function SqlSelectToJsonTable($result,$withNames=false){
            // result a mysqli::query object, 
            // withNames: boolean, should the column names be returned as first row
            $return_arr = array();
            echo $result->num_rows;
            if ($result->num_rows > 0){
                if($withNames == true){
                    $return_arr[0] = array();
                    $fields = $result->fetch_fields();
                    foreach ($fields as $field){
                        echo "column: ".$field->name." ";
                        array_push($return_arr[0],$field->name);
                    }
                }
                while($row = $result->fetch_assoc()) {
                    $return_arr[]= array_values($row);
                }
            } else {
                echo "0 results";
            }
            return json_encode($return_arr);
        }
    

    Used as in the following:

        <?php
        $servername = "localhost";
        $username = "user";
        $password = "password";
        $dbname = "test";
    
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
    
        $sql = "SELECT id, title FROM Posts";
        $result = $conn->query($sql);
    
        $jsonTable = SqlSelectToJsonTable($result);
        echo '<br/>'.$jsonTable;
    
        echo "<script type=\"text/javascript\">
            var jsTable = JSON.parse('".$jsonTable."');
            </script>";
    
        $conn->close();
        ?>
    

    Where jsTable will effectively be an array of arrays. Note the option withNames allowing to add the column names as the first row, usefull if you try to pass this array to javascript for google visualization.

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

报告相同问题?

悬赏问题

  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题