【问题标题】:Creating JSON table from SQL query从 SQL 查询创建 JSON 表
【发布时间】:2013-09-11 00:22:58
【问题描述】:

我想根据 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);

【问题讨论】:

  • 对不起,任何令人畏惧的术语,我对此很陌生。 JSON字符串就是我想说的。

标签: php mysql sql json phpmyadmin


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    nitpick:没有“json 表”之类的东西。有 JSON 字符串,它们是表示其他语言的数据结构的明文字符串,例如javascript。

    您的问题是您正在尝试遍历 mysqli 结果句柄。这通常是单个 ROW 数据,而不是整个结果集。

    你应该有更多类似的东西:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 2021-06-10
      • 2013-09-24
      • 2015-02-15
      • 2017-06-05
      • 2021-09-20
      • 1970-01-01
      • 2020-10-28
      相关资源
      最近更新 更多