我有一个从DB获得的多维数组。 Array每小时都有一些视图,这些视图作为视图记录在数据库中,它看起来像这样:
array:11 [▼
0 => array:2 [▼
"hour" => 0
"views" => 1
]
1 => array:2 [▼
"hour" => 1
"views" => 1
]
2 => array:2 [▼
"hour" => 4
"views" => 1
]
...and so on
]
我需要创建一个包含2个小时范围的视图数量的新数组。因此,例如从上面显示的数组中,我想得到一个数组,其中0到2之间的时间视图数量,2和2-4,在这种情况下将为0,依此类推。
答案 0 :(得分:1)
你可以在Mysql查询中执行:
select floor(hour/2) range, sum(views) sum
from thetable
group by range
答案 1 :(得分:1)
您可以使用foreach创建新数组。
<?php
$your_array = [0 => [
"hour" => 0,
"views" => 4
],
1 => [
"hour" => 1,
"views" => 12
],
2 => [
"hour" => 4,
"views" => 1
],
3 => [
"hour" => 2,
"views" => 9
],
4 => [
"hour" => 21,
"views" => 19
]
];
foreach ($your_array as $value){
for($i=0;$i<=22;$i=$i+2){
$j=$i+2;
if($value['hour']>=$i && $value['hour']<$j){
isset($result[$i.'-'.$j])?$result[$i.'-'.$j]+=$value['views']:$result[$i.'-'.$j]=$value['views'];
}
}
}
print_r($result);
答案 2 :(得分:0)
尝试以下代码。
$arr = [0 => [
"hour" => 0,
"views" => 1
],
1 => [
"hour" => 1,
"views" => 1
],
2 => [
"hour" => 4,
"views" => 1
]];
foreach($arr as $row)
{
if($row['hour'] >= 0 && $row['hour'] <= 2)
{
$newArr['0-2'] = isset($newArr['0-2']) ? ($newArr['0-2'] + 1) : 1;
}
if($row['hour'] > 2 && $row['hour'] < 4)
{
$newArr['2-4'] = isset($newArr['2-4']) ? ($newArr['2-4'] + 1) : 1;
}
}
print_r($newArr);
<强>输出强>
Array
(
[0-2] => 2
)