[英]PHP- Sorting multidimensional array into another by range of numbers
I have a multidimensional array that I get from DB. 我有一个从数据库获得的多维数组。 Array has a number of views by each hour that is logged in the DB as a view, and it looks like this:
数组每小时都有许多视图,这些视图作为视图记录在数据库中,如下所示:
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
]
I need to make a new array that will contain number of views for range of 2 hours. 我需要制作一个新数组,其中包含2小时范围内的视图数。 So for example from the array shown above I would like to get an array with, number of views for time between 0-2, that would 2, and for 2-4, would be 0 in this case, and so on.
因此,例如,从上面显示的数组中,我想得到一个数组,在这种情况下,0-2之间的视图数量为2,而2-4的视图数量为0,依此类推。
You can do it in Mysql query: 您可以在Mysql查询中执行此操作:
select floor(hour/2) range, sum(views) sum
from thetable
group by range
You can just use a foreach to create a new array. 您可以只使用一个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);
Try below code. 尝试下面的代码。
$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);
Output 输出量
Array
(
[0-2] => 2
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.