无法传递数组数据

时间:2019-09-28 08:06:43

标签: php arrays json mysqli

我正在尝试在$data中创建一个数组,但是没有发生。我正在使用此代码制作每日销售图表。

$data = array();
for ($i = 0; $i <= 10; $i++) {
    $billdate = date('d-m-Y', strtotime("-$i day"));
    $sqlQuery = "select sum(amount),bill_date from msr_bills WHERE bill_date='$billdate' ";
    $result = mysqli_query($con, $sqlQuery);

    $fetchamount = mysqli_fetch_row($result);
    $sum = $fetchamount[0];

    $data = new \stdClass();
    $data->bill_date = $billdate;
    $data->amount = $sum;
    $report_JSON = json_encode($data);

    echo  $report_JSON.",";
}

2 个答案:

答案 0 :(得分:1)

您可以将循环合并到一个查询中,然后遍历结果:

$data = array();
$billdate = date('Y-m-d', strtotime('-10 day'));
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
             FROM msr_bills
             WHERE bill_date >= '$billdate'
             GROUP BY bill_date";
$result = mysqli_query($sqlQuery);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = (object)$row;
    }
    $report_JSON = json_encode($data);
    echo  $report_JSON;
}

请注意,您的日期格式与以Y-m-d格式存储的MySQL日期不兼容,我已经在代码中进行了更改。如果您的bill_date列实际上是以d-m-Y格式存储的文本字段,则需要在查询中进行如下转换:

$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
             FROM msr_bills
             WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= '$billdate'
             GROUP BY bill_date";

请注意,实际上您可以使用日期算术对SQL查询内部的$billdate进行计算:

$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
             FROM msr_bills
             WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= CURDATE() - INTERVAL 10 DAY
             GROUP BY bill_date";

如果您正在运行MySQL 8.0+,则可以在MySQL中完成整个操作:

$sqlQuery = "SELECT JSON_ARRAYAGG(data) AS data
             FROM (SELECT JSON_OBJECT('bill_date', bill_date, 'amount', SUM(amount)) AS data
                   FROM msr_bills
                   WHERE bill_date >= CURDATE() - INTERVAL 10 DAY
                   GROUP BY bill_date) d";
$result = mysqli_query($sqlQuery);
if ($result) {
    $row = mysqli_fetch_assoc($result);
    $report_JSON = $row['data'];
    echo $report_JSON;
}

Demo on dbfiddle

答案 1 :(得分:0)

将回声置于循环之外。删除代码$report_JSON = json_encode($data);

$respnseArr = array();

{
.
.
.
  $respnseArr[] = $data;
}

echo json_encode($respnseArr);