获取数组中的数据库值

时间:2017-10-31 10:02:02

标签: php mysql arrays

我有一个包含订单日期的数据库列。我需要在每个月获得订单数量。目前根据我的代码我使用switch语句。我知道它不是一种简洁的编码方式。所以我需要知道有什么办法可以让它更精确。我需要以下面的方式输出以在Javascript中形成图表。所以我希望有人可以帮助我。

提前致谢。

$datayearly = array(
    'labels' => array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'),
    'series' => array(array(
        'name' => 'series-1',
        'data' => array($jan, $feb, $mar, $apr, $may, $jun, $jul, $aug, $sep, $oct, $nov, $dec)
    ))
);

用于从数据库中获取的Php代码和数据库的屏幕截图。 enter image description here

$thisyear =  date("Y");
$jan=$sep=$feb=$mar=$apr=$may=$jun=$jul=$aug=$sep=$oct=$nov=$dec=0;
$year[0] =0;
$stmt = $conn1->prepare("SELECT * FROM salessummary WHERE dateoforder LIKE :key");
$stmt->execute(array('key' => "%{$thisyear}%"));
foreach ($stmt as $row) {
    $month = date('m', strtotime($row['dateoforder']));
    switch ($month) {
        case "01":
        $jan++;
        case "02":
        $feb++;
        case "03":
        $mar++;
        case "04":
        $apr++;
        case "05":
        $may++;
        case "06":
        $jun++;
        case "07":
        $jul++;
        case "08":
        $aug++;
        case "09":
        $sep++;
        case "10":
        $oct++;
        case "11":
        $nov++;
        case "12":
        $dec++;
    }       
}
$high = max($jan, $feb, $mar, $apr, $may, $jun, $jul, $aug, $sep, $oct, $nov, $dec) + 10;
$datayearly = array(
    'labels' => array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'),
    'series' => array(array(
        'name' => 'series-1',
        'data' => array($jan, $feb, $mar, $apr, $may, $jun, $jul, $aug, $sep, $oct, $nov, $dec)
    ))
);
$temp = json_encode($datayearly);

2 个答案:

答案 0 :(得分:2)

这将有效:

SELECT COUNT(*), DATE_FORMAT(dateoforder,'%Y-%m') as Month 
FROM orders 
GROUP BY DATE_FORMAT(dateoforder,'%Y-%m');

如果你想要的是" 2017-10"作为月份,将第一个DATE_FORMAT更改为您想要的任何格式。有关详细信息,请参阅the docs

答案 1 :(得分:1)

这是否满足您的需求?

$thisyear =  date("Y");
$months = array(
    1 => 0,
    2 => 0,
    3 => 0,
    4 => 0,
    5 => 0,
    6 => 0,
    7 => 0,
    8 => 0,
    9 => 0,
    10 => 0,
    11 => 0,
    12 => 0
);
$year[0] = 0;

$stmt = $conn1->prepare("SELECT * FROM salessummary WHERE dateoforder LIKE :key");
$stmt->execute(array('key' => "%{$thisyear}%"));

foreach ($stmt as $row) {
    $month = date('m', strtotime($row['dateoforder']));
    $months[intval($month)]++;  
}

$high = max($months) + 10;
$datayearly = array(
    'labels' => array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'),
    'series' => array(array(
        'name' => 'series-1',
        'data' => array_values($months)
    ))
);
$temp = json_encode($datayearly);