Php 从mysql查询创建数组
我的MySQL数据库中有类似的东西Php 从mysql查询创建数组,php,mysql,Php,Mysql,我的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中,我需要知道哪种产品在哪一天销售的频率。 因此:2015年1月1日产品1一次,产品2一次,2015年2月4日产品1两次,
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中,我需要知道哪种产品在哪一天销售的频率。
因此:2015年1月1日产品1一次,产品2一次,2015年2月4日产品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
所以我做了一个普通的查询:从表中按日期排序选择日期
我以数组中的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\u count\u values
过滤天数,以了解出现的天数,但我无法找到如何将产品连接到天数
编辑:德怀特的解决方案:
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
工作很好,现在我已经在每一行哪种产品在哪一天销售多久
我现在遇到的问题是,如果我想使用这些数据来填充google堆叠图表,如下图所示,结果中的每一行表示google图表中的on列。因此,对于上面的例子,我将在2015年1月1日在我的图表中有两个条目(一个条用于产品1,一个条用于产品2),但我希望每天的产品数量被叠加。因此,2015年1月1日只有一个条目,其中当天销售的产品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;
}
这将导致如下结果:
但我需要将这些值相互叠加,如下所示:
在SQL中这样做会容易得多。比如:
SELECT product, date, COUNT(*)
FROM tablename
GROUP BY product, date.
然后,每一行是按日期列出的一种产品的销售数量。您能更清楚地说明您需要什么格式的数据吗?您的产品的最大数量是3或3以上?我需要一个json对象,我想从数组中提取它,这样我就可以动态填充google堆叠图表。如果某个产品在给定日期丢失,这意味着该产品在该日期没有售出。