从SQL查询创建JSON表

时间:2013-09-06 19:53:37

标签: php mysql sql json phpmyadmin

我想根据SQL查询的结果创建一个JSON表。我在phpMyAdmin上尝试了查询并且它是正确的(我得到了我想要的数据)但是当我尝试使用下面的代码将其转换为JSON表时,结果是一个具有正确结构但没有值的表

/* select all moches from the table moches */
$query="SELECT municipio, SUM(moche) AS moche FROM moches GROUP BY municipio";
$result = $mysqli->query($query);

     $rows = array();
     $table = array();
     $table['cols'] = array(

       array('label' => 'Municipio', 'type' => 'string'),           
       array('label' => 'Cantidad total en moches', 'type' => 'number')

                );

     foreach($result as $r) {

                      $temp = array();

                      //Create the different states

                      $temp[ ] = array('v' => (string) $r['municipio']); 

                      // Total de moches

                      $temp[ ] = array('v' => (int) $r['moche']); 
                      $rows[ ] = array('c' => $temp);


                    }

      $table['rows'] = $rows;

      // convert data into JSON format
      $jsonTable = json_encode($table);

2 个答案:

答案 0 :(得分:2)

phpMyAdmin允许以JSON格式导出,也许这可以帮助你。

答案 1 :(得分:1)

nitpick:没有“json table”这样的东西。有JSON字符串,它们是明文字符串,表示某种其他语言的数据结构,例如的JavaScript。

你的问题是你试图遍历一个mysqli结果句柄。这通常只是一个 ROW 数据,而不是整个结果集。

你应该有更多的东西:

$result = $mysqli->query($sql);

$temp = array();
while($row = $result->fetch_row()) {
    $temp[] = $row;
}
echo json_encode($temp);