【问题标题】:Outputting SQL query as line by line JSON将 SQL 查询输出为逐行 JSON
【发布时间】:2015-02-20 10:02:06
【问题描述】:

我的 SQL 查询是选择日期并进行计数,以及按日期分组。

我不知道如何逐行输出JSON输出。

 $sql = "SELECT DATE(timestamp), COUNT(eventid)
 FROM `tablex`
 WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
 GROUP BY DATE(timestamp) ";

 $stream = mysqli_query($conn, $sql);


if (mysqli_num_rows($stream) > 0) {

   while($row = mysqli_fetch_assoc($stream)) {

     // Is this where I should echo JSON? 
     // The problem is I'm not retrieving records but count and doing
     // a grouping

     }}

【问题讨论】:

  • 你能把你想要的格式显示为o/p吗?
  • 输出格式应该是:[{ "timestamp": "2015-02-20", "count": 417 }]

标签: php mysql json count grouping


【解决方案1】:

使用mysqli_fetch_array(),也可以使用mysql_num_rows()进行计数:

$sql = "SELECT DATE(timestamp), COUNT(eventid)
 FROM `tablex`
 WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
 GROUP BY DATE(timestamp) ";

 $stream = mysqli_query($conn, $sql);

if (mysqli_num_rows($stream) > 0) {
   $rowCount = mysql_num_rows($result);
   while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
       // Process JSON here use $row[0], $row[1], and so
   }
}

【讨论】:

    【解决方案2】:

    无论您想以 JSON 字符串的形式返回什么,都应该始终将数据写入单个数组,然后使用这个名为 json_encode() 的漂亮的 PHP 小函数。例如:

    $sql = "SELECT
       DATE(timestamp) as date_timestamp,
       COUNT(eventid) as count_eventid
       FROM `tablex`
       WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
       GROUP BY DATE(timestamp);";
    
    $stream = mysqli_query($conn, $sql);
    
    // prepare return array
    $mydata = array(
        'eventcount' => 0
    );
    
    if (mysqli_num_rows($stream) > 0) {
        while($row = mysqli_fetch_assoc($stream)) {
            // just collect your data here, do not JSONify here
            $mydata['eventcount'] += $row['count_eventid'];
        }
    }
    // We got all our data, so return JSON encoded array
    echo json_encode($mydata);
    

    你会得到类似的东西

    {"eventcount":"1234"}
    

    【讨论】:

    • 我得到 {"eventcount":0} 作为输出。我如何包括。事件计数旁边的时间戳?
    • 如果你得到 0,那么你很可能根本不会检索任何行。您应该首先检查您的 SQL 语句是否检索到任何记录。您可能还想试试这个: $mydata = array( ); if (mysqli_num_rows($stream) > 0) { while($row = mysqli_fetch_assoc($stream)) { // 按日期分组计数 $mydata[$row['date_timestamp']] = $row['count_eventid']; } }
    【解决方案3】:

    我设法得到一个输出:

    $stream = mysqli_query($conn, $sql);
    
    $lines = array();
    while($line = mysqli_fetch_assoc($stream)) {
          $llines[] = $line;
    }
    
    print json_encode($lines);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      相关资源
      最近更新 更多