gpt4 book ai didi

php - 从 mysql 查询创建数组

转载 作者:行者123 更新时间:2023-11-29 01:55:40 28 4
gpt4 key购买 nike

我的 MySQL 数据库中有类似的东西。

 Date            product 
2015-01-01 1
2015-01-01 2
2015-02-03 3
2015-02-04 1
2015-02-04 1
2015-02-04 3

我需要在 PHP 中知道哪种产品在哪一天的销售频率。所以:01.01.2015 产品 1 一次,产品 2 一次,04.02.2015 产品 1 两次,产品 3 一次 ...

像这样:

Date                product 1  product 2 product 3 
2015-01-01 1 1 0 //how many times
2015-02-03 0 0 1
2015-02-04 2 0 1

所以我做了一个普通查询:SELECT date from table order by date.

我在数组中将对象作为 stdClass 返回,但现在我不知道如何获取我需要的信息。

我试过类似的东西

$array=array();

foreach ($result as $key => $value) {
$time = ($result[$key]->date);

$temp[] = array(
'date' => $time,
'product 1' => '2', //equals times
'product 2' => '3',
'product 3' => '4',
'product 4' => '4'

);
$arrayBig[] = $temp;

}

并且还使用array_count_values 来过滤日期以了解哪些日期出现,但我无法找到如何将产品连接到日期。

编辑:DWright 的解决方案:

 SELECT product, date, COUNT(*)
FROM tablename
GROUP BY product, date.

日期产品数量(*) 2015-01-01 1 1 2015-01-01 2 2 2015-02-03 3 1

工作正常,现在我在每一行中都有在哪一天销售的产品的频率。

我现在遇到的问题是,如果我想使用此数据来填充谷歌堆叠图表,如下所示,结果中的每一行都代表谷歌图表图表中的列。因此,对于上面的示例,我将在 2015 年 1 月 1 日在我的图表中有两个条目(一个用于产品 1,一个用于产品 2),但我希望每天堆叠产品数量。所以 01.01.2015 应该只有一个条目,当天销售的产品 1 的数量和当天销售的产品 2 的数量相互叠加,

$result = $sql statement

foreach ($result as $key => $value ) {
$typeOfProduct = $value->product;
$amount = $value->anzahl;
$time = $value->Date;
switch ($typeOfProduct) {
case 1:
$produt1 = $amount;
break;
case 2: //twitter
$product2 = $amount;
break;
case 3:
$product3 = $amount;
break;
default:

break;
}
$rows = array();
$table = array();
$table['cols'] = array(

array('label' => 'Datum', 'type' => 'date'),
array('label' => 'product 1', 'type' => 'number'),
array('label' => 'product 2', 'type' => 'number'),
array('label' => 'product 3', 'type' => 'number')

);

$day = date('d', strtotime( $time ) );
$month = date('m', strtotime( $time ) );
$monthNew = $month - 1;
$year = date('Y', strtotime( $time ) );


$temp[] = array('v' => "Date( $year, $monthNew, $day )");
$temp[] = array('v' => $product1 );
$temp[] = array('v' => $product2);
$temp[] = array('v' => $product3 );

$rows[] = array('c' => $temp);
$table['rows'] = $rows;
}

这将导致类似这样的结果:https://jsfiddle.net/api/post/library/pure/

但我需要将这些值堆叠在一起,如下所示: https://jsfiddle.net/api/post/library/pure/

最佳答案

在 SQL 中,这对您来说会容易得多。像这样的东西:

 SELECT product, date, COUNT(*)
FROM tablename
GROUP BY product, date.

然后每一行都是按日期排列的一种产品,以及该日期的售出数量。

关于php - 从 mysql 查询创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958880/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com