向数组添加零值

Adding zero values to an array

我正在对保存各种客户订单的数据库执行以下查询。

SELECT WEEKDAY(orderDateTime) Date, COUNT(clientID) totalCount FROM orders WHERE YEARWEEK(orderDateTime,1) = YEARWEEK(NOW(),1) GROUP BY DATE(orderDateTime)

SELECT WEEKDAY(orderDateTime) Date, COUNT(clientID) totalCount FROM orders WHERE YEARWEEK(orderDateTime,1) = YEARWEEK(NOW() - INTERVAL 1 WEEK,1) GROUP BY DATE(orderDateTime)

SELECT DATE_FORMAT(orderDateTime, '%Y') as 'year', DATE_FORMAT(orderDateTime, '%m') as 'month', COUNT(clientID) as 'total' FROM orders GROUP BY DATE_FORMAT(orderDateTime, '%Y%m')

我正在将这些构建成一个数组,其中月/日数字与计数值相对应:

[[0, 1], [1,4]...]

我正在使用 Flot 来绘制这些图形,但发生的是没有订单的任何几天或几个月它没有值(显然)所以你得到的是这样的:

[[0, 1], [1,4], [6,12]] 这使得图形绘制错误。

试图解决的问题是如何填充它,使其看起来像:

[[0, 1], [1,4], [2,0], [3,0], [4,0], [5,0], [6,12]] <- - 对于工作日和,

[[1, 1], [2,4], [3,0], [4,0], [5,0], [6,0], [7,12], [8 ,0], [9,12], [10,0], [11,0], [12,0]] <-- 每个月。

我正在使用 PHP 作为主要内容。如果我不清楚,任何指示将不胜感激和抱歉。询问您是否需要任何说明。

PHP:

$thisWeekA = array();

$thisWeekQ = $database->query("SELECT WEEKDAY(orderDateTime) Date, COUNT(clientID) totalCount FROM orders WHERE YEARWEEK(orderDateTime,1) = YEARWEEK(NOW(),1) GROUP BY DATE(orderDateTime)")->fetchAll();

foreach($thisWeekQ as $thisweek){
    $thisWeekA[] = array( $thisweek['Date'], $thisweek['totalCount'] );
}

array(2) {
  [0]=>
  array(4) {
    ["Date"]=>
    string(1) "2"
    [0]=>
    string(1) "2"
    ["totalCount"]=>
    string(1) "3"
    [1]=>
    string(1) "3"
  }
  [1]=>
  array(4) {
    ["Date"]=>
    string(1) "3"
    [0]=>
    string(1) "3"
    ["totalCount"]=>
    string(1) "2"
    [1]=>
    string(1) "2"
  }
}

在您的 php 中使用 for 循环的每周数据更新为, 逻辑一周只有 7 天而不是使用结果数据中的 foreach 我们可以使用 for 循环 7 天

即,同样使用多年

$thisWeekA = array();    
$thisWeekQ = $database->query("SELECT WEEKDAY(orderDateTime) Date, COUNT(clientID) totalCount FROM orders WHERE YEARWEEK(orderDateTime,1) = YEARWEEK(NOW(),1) GROUP BY DATE(orderDateTime)")->fetchAll();

    for ($i = 0; $i <= 6; $i++) {
        if ($thisWeekQ[$i]['Date'] == $i) {
            $thisWeekA[$i][] = array($thisWeekQ[$i]['Date'], $thisWeekQ[$i]['totalCount']);
        } else {
            $thisWeekA[$i][] = array($i, 0);
        }
    }

您可能更愿意考虑像这样构建数组:

var dow = [];
dow[0] = 1;
dow[1] = 4;
dow[6] = 12;

此时您可以为图表填充数组

var chartData = [];
for (var i=0; i<7; i++){
    chartData[i] = [i, (dow[i] === undefined ? 0 : dow[i])];
}

我想出了一个办法。感谢您为我指出 For 循环的方向!

这就是我想出的方法!

function arrayhunt($products, $field, $value){

   foreach($products as $key => $product){

        if ($product[$field] == $value){
            return $key;
        }
   }
   return false;
}


    $i = 0;
    for ($i = 0; $i <= 6; $i++) {

        $keys = arrayhunt($thisWeekQ,"Date",$i);

        if($keys !== FALSE){
            $thisWeekA[] = array($thisWeekQ[$keys]['Date'], $thisWeekQ[$keys]['totalCount']);
        } else {
            $thisWeekA[] = array($i, 0);
        }

        $keys = "";
    }

希望以后有人觉得这有用。