我对mysql有这个查询:
SELECT HOUR(time),COUNT(*) FROM pageview WHERE time >= DATE_SUB(NOW(),INTERVAL 12 HOUR) GROUP BY HOUR(time)
例如,这是输出:
Array
(
[0] => Array
(
[HOUR(time)] => 1
[COUNT(*)] => 1
)
[1] => Array
(
[HOUR(time)] => 10
[COUNT(*)] => 4
)
[2] => Array
(
[HOUR(time)] => 11
[COUNT(*)] => 5
)
)
但是我想要像这样的输出
Array
(
[1] => 1
[10] => 4
[11] => 5
)
数组索引应该是[HOUR(time)]
的值。
我希望直接通过更改查询。
要获取数据我使用:
$stmt = $db->prepare($query);
$result = $stmt->execute();
$views = $stmt->fetchAll();
答案 0 :(得分:1)
mysql结果中的索引自动创建,通过第一个数组实现目标循环并根据需要创建新数据
$result = array();
foreach($views as $row) {
$result[$row['HOUR(time)']] = array( 'COUNT(*)' => $row['COUNT(*)']);
}
print_r($result); // check output
或更简单的表格
$result = array();
foreach($views as $row) {
$result[$row['HOUR(time)']] = $row['COUNT(*)'];
}
print_r($result); // check output
答案 1 :(得分:0)
试试这个
$res = array();
foreach($views as $data)
{
$res[$data['HOUR(time)']] = array( 'COUNT(*)' => $data['COUNT(*)']);
}
print_r($res);