向数组添加零值

时间:2016-05-01 17:27:05

标签: php sql flot

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

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"
  }
}

3 个答案:

答案 0 :(得分:1)

每周数据用于循环在你的php更新它, 逻辑仅在一周内7天而不是从结果数据中使用foreach我们可以使用for循环七天

即同样多年使用

$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);
        }
    }

答案 1 :(得分:1)

您可能想要考虑更像这样构建数组:

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])];
}

答案 2 :(得分:0)

我设法找到了一种方法。谢谢你指点我的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 = "";
    }

希望以后有人发现这个有用。