我需要在我的数组中保存一些数字。这些数字是用户在我的网站上停留的时间。
喜欢:
duration quantity
0-30 sek 50
30sek-2min 100
....
所以 50 个用户在我的网页上大约是 0-30 瑞典克朗。
现在我有这个数组 $visit_length 和这个输出:
Array
(
[0] => 3636
[1] => 3637
[2] => 3
[3] => 40
[4] => 9
)
这是用户在我的网站上停留多少秒的持续时间
现在我想做一个新的数组。在这个新数组之前,我需要一个 foreach 和一个 if/else 或开关/案例
喜欢这个:
$dauer_result = [];
foreach ($visit_lenght as $lenght) {
switch ($lenght) {
case $lenght < 30:
$dauer_result = count($lenght);
continue;
case $lenght > 30 and $lenght < 120:
$dauer_result = count($lenght);
continue;
case $lenght > 120 and $lenght < 300:
$dauer_result = count($lenght);
continue;
case $lenght > 300 and $lenght < 900:
$dauer_result = count($lenght);
continue;
case $lenght > 900 and $lenght < 1800:
$dauer_result = count($lenght);
continue;
case $lenght > 1800 and $lenght < 3600:
$dauer_result = count($lenght);
continue;
case $lenght > 3600:
$dauer_result = count($lenght);
}
}
当然,这说明如果$length大于"秒数",则将 count($length( 的结果保存在新数组 $dauer_length 中
例如:$visit_length 变量的前两个键是 3636 和 3637
这意味着它们处于最后一种情况。 所以在 $dauer_result 中应该写成 2,因为两者都高于 3600。
或者也许你们中的某个人有另一种更好的方法。好吧,我希望你明白我想说的话。我的英语不是最好的。
感谢您的帮助:)
---------------------更新:-------------------
已解决的代码:
$dauer_result = array('<30'=>0, '30-120'=>0, '120-300'=>0, '300-900'=>0, '900-1800'=>0, '1800-3600'=>0, '>3600'=>0);
foreach ($visit_lenght as $lenght) {
switch ($lenght) {
case $lenght < 30:
$dauer_result['<30'] +=1 ;
continue;
case $lenght > 30 and $lenght < 120:
$dauer_result['30-120'] +=1 ;
continue;
case $lenght > 120 and $lenght < 300:
$dauer_result['120-300'] +=1 ;
continue;
case $lenght > 300 and $lenght < 900:
$dauer_result['300-900'] +=1 ;
continue;
case $lenght > 900 and $lenght < 1800:
$dauer_result['900-1800'] +=1 ;
continue;
case $lenght > 1800 and $lenght < 3600:
$dauer_result['1800-3600'] +=1 ;
continue;
case $lenght 3600:
$dauer_result['>3600'] +=1 ;
continue;
}
}
我想你正在寻找
$dauer_result = array('<30'=>0, '30-120'=>0, '120-300'=>0, '300-900'=>0, '900-1800'=>0, '1800-3600'=>0, '>3600'=>0);
foreach ($visit_lenght as $lenght) {
switch ($lenght) {
case $lenght < 30:
$dauer_result['<30'] +=1 ;
continue;
case $lenght > 30 and $lenght < 120:
$dauer_result['30-120'] +=1 ;
continue;
case $lenght > 120 and $lenght < 300:
$dauer_result['120-300'] +=1 ;
continue;
case $lenght > 300 and $lenght < 900:
$dauer_result['300-900'] +=1 ;
continue;
case $lenght > 900 and $lenght < 1800:
$dauer_result['900-1800'] +=1 ;
continue;
case $lenght > 1800 and $lenght < 3600:
$dauer_result['1800-3600'] +=1 ;
continue;
case $lenght 3600:
$dauer_result['>3600'] +=1 ;
continue;
}
}
这可以通过使用array_filter
轻松完成,它使用自定义函数从数组中过滤值。下面是一个示例:
$visit_length = array(3636, 3637, 3, 40, 9 );
function length_filter($var)
{
return ($var > 3600);
}
$result = array_filter($visit_length, 'length_filter');
变量 $result
现在包含一个数组,该数组仅包含高于 3600
的值。