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

时间:2011-04-19 13:34:44

标签: php json

这里我有一些功能来阅读我的表

<?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);
        }
?>

下面的代码我调用get_all_record函数并返回结果我使用json_encode转换为json对象

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

    echo json_encode($myItem);
?>

我的输出如下

[{"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"}]

但我需要JSON对象,如下所示

{ "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"]
] }

你能不能请任何人帮助创建上面的json对象。

2 个答案:

答案 0 :(得分:0)

请尝试使用以下代码进行编码:

echo json_encode($myItem, true);

答案 1 :(得分:0)

json_encode获取具有名称/值对的数组。您只需要改变值。 最好的解决方案是使用

  

和mysql_fetch_row($结果)

获取一个数值数组,将其转换为您首选的json格式。


如果您稍后需要名称/值对,您仍然可以使用

  

mysql_fetch_assoc($结果)

以这种方式创建第二个数组:

  

$ mySoonToBeJsonData =   array_values($ myrow);

这将从关联数组中删除名称