dotibrb048760 2011-04-19 13:34
浏览 57
已采纳

我尝试创建json对象,但我无法创建

Here I have some function to read my table

<?php
 public function get_all_record($table, $fields = "*"){

            $sql = "SELECT $fields FROM $table";

            $result = $this->sqlordie($sql);

            $xx=0;
            while($row = mysql_fetch_assoc($result))
              {
                $myrow[$xx] = $row;
                $xx++;
              }


             mysql_free_result($result);
             return $myrow;

        }
     private function sqlordie($sql) {

            $return_result = mysql_query($sql, $this->conn);
            if($return_result) {
                return $return_result;
            } else {
                $this->sql_error($sql);
            }
        }

        private function sql_error($sql) {
            echo mysql_error($this->conn).'<br>';
            die('error: '. $sql);
        }
?>

Below code I am calling the get_all_record function and return result I am convert into json object using json_encode

 <?php
 $myItem = get_all_record("mc_category","category_id,category_name,category_description");

    echo json_encode($myItem);
?>

I am getting output as below

[{"category_id":"2","category_name":"book","category_description":"all type of books"},{"category_id":"3","category_name":"book","category_description":"all type of books"},{"category_id":"4","category_name":"Phone","category_description":"All type of phones"},{"category_id":"5","category_name":"Phone","category_description":"All type of phones"}]

But I need JSON object as below

{ "aaData": [
    ["Trident","Internet Explorer 4.0","Win 95+","4","X"],
    ["Trident","Internet Explorer 5.0","Win 95+","5","C"],
    ["Trident","Internet Explorer 5.5","Win 95+","5.5","A"],
    ["Trident","Internet Explorer 6","Win 98+","6","A"],
    ["Trident","Internet Explorer 7","Win XP SP2+","7","A"]
] }

Could you please any one help to create above json object.

  • 写回答

2条回答 默认 最新

  • dqd22496 2011-04-19 13:49
    关注

    json_encode gets an array with name/value pairs. You want just the values instead. The best solution is to use

    mysql_fetch_row($result)

    to get an numerical array, that gets converted to your preferred json format.


    If you need the name/value pairs somewhere later you can still use

    mysql_fetch_assoc($result)

    and create a second array this way:

    $mySoonToBeJsonData = array_values($myrow);

    this removes the names from the associative array

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测