dotibrb048760
dotibrb048760
2011-04-19 13:34

我尝试创建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 dqd22496 10年前

    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

    点赞 评论 复制链接分享
  • douxing9228 douxing9228 10年前

    Try using the following to encode instead:

    echo json_encode($myItem, true);
    
    点赞 评论 复制链接分享

相关推荐