PHP MySQL-获取前几天的值和条目总数

时间:2018-12-27 10:45:25

标签: php mysql arrays

我必须将过去几天的总值放入一个数组中。 首先,我有一个数组来获取最后的日子:

$today = date('Y-m-d');
$ldays = [];
$db = 6;
for($i=-$db; $i<=0; $i++) {
    array_push($ldays, date('Y-m-d', strtotime("$i days")));
}

//this will produce an array like this:
array (size=7)
  0 => string '2018-12-21' (length=10)
  1 => string '2018-12-22' (length=10)
  2 => string '2018-12-23' (length=10)
  3 => string '2018-12-24' (length=10)
  4 => string '2018-12-25' (length=10)
  5 => string '2018-12-26' (length=10)
  6 => string '2018-12-27' (length=10)

现在,我从数据库中提取每天的总值。

SELECT COUNT(id) as total, data FROM users WHERE data >= '2018-12-21' GROUP BY data ORDER BY data ASC

输出将是这样的数组:

array (size=2)
  0 => 
    array (size=2)
      'total' => int 1
      'data' => string '2018-12-21' (length=10)
  1 => 
    array (size=2)
      'total' => int 1
      'data' => string '2018-12-24' (length=10)

如您所见,该数组缺少了几天,所以我需要越过2个数组,看看2个数组中是否存在一天:

$response = [];

for($i=0; $i<count($ldays); $i++) {
    if(in_array($ldays[$i], array_column($rows_d, 'data'))) {
        $response[$ldays[$i]] = 'yes';
    }
    else {
        $response[$ldays[$i]] = 'no';
    }
}

//this will make an array like so:
array (size=7)
  '2018-12-21' => string 'yes' (length=3)
  '2018-12-22' => string 'no' (length=2)
  '2018-12-23' => string 'no' (length=2)
  '2018-12-24' => string 'yes' (length=3)
  '2018-12-25' => string 'no' (length=2)
  '2018-12-26' => string 'no' (length=2)
  '2018-12-27' => string 'no' (length=2)

但是,在设置“是”和“否”之后,我希望数组类似于

array(size=7)
  '2018-12-21' => int 1
  '2018-12-22' => int 0 
  '2018-12-23' => int 0 
  '2018-12-24' => int 1 
  '2018-12-25' => int 0 
  '2018-12-26' => int 0 
  '2018-12-27' => int 0 

如果执行此操作,我会不断收到错误消息:

if(in_array($ldays[$i], array_column($rows_d, 'data'))) {
    $response[$ldays[$i]] = $rows[$i]['total'];
}
else {
    $response[$ldays[$i]] = 0;
}

我猜这是因为行数组只有2个条目,而天数组只有7个条目。那么,我如何获得它呢? tks。

2 个答案:

答案 0 :(得分:0)

与其将array_searcharray_column结合使用,而不是使用in_array,而是在$rows数组中找到适当的索引:

if (($k = array_search($ldays[$i], array_column($rows_d, 'data'))) !== false) {
    $response[$ldays[$i]] = $rows_d[$k]['total'];
}
else {
    $response[$ldays[$i]] = 0;
}

请注意,您在代码中同时使用了$rows$rows_d,我假设在两种情况下都应该使用$rows_d

答案 1 :(得分:0)

看起来更漂亮

$today = date('Y-m-d');
    $ldays = [];
    $db = 6;
    for($i=-$db; $i<=0; $i++) {
        $ldays[date('Y-m-d', strtotime("$i days"))] = 0;
    }

    $dbResult = [['total' => 1,'data' => '2018-12-21'],['total' => 2,'data' => '2018-12-24']]

    foreach ($dbResult as $v) {
        $ldays[$v['data']] = $v['total'];
    }

    var_dump($ldays);