我正在尝试过滤一些日志,就像我需要它们一样,并尝试动态。我有一些域名,我正在尝试从中过滤掉一些内容,而且这一切都像我想要的那样 - 但现在我更改了域名,现在我的代码不再起作用了。它说一个变量没有定义。
$sp_bots = shell_exec("grep bot | awk '{print $12}' /var/www/laravel/logs/vhosts/zahnmedizinisches-fachzentrum-berlin.de.log");
$array_sp_bots = explode("\n", $sp_bots);
$all_bots = array();
foreach($array_sp_bots as $bots){
if(strpos($bots, "bot")){
$all_bots[] = $bots;
}
}
# count values of strings in array
if (!empty( $all_bots )) {
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}
在我的回报中:
return view('/domains/data', [
'count_bots' => $count_bots,
'bot_keys' => $bot_keys,
'mostOccuring' => $mostOccuring,
]);
但是我的回归中的所有三个变量都是未定义的..有谁知道为什么?
答案 0 :(得分:3)
您必须在循环之前将数组初始化为空数组:
$all_bots = array(); //init the empty array
foreach($array_sp_bots as $bots)
{
if(strpos($bots, "bot"))
{
$all_bots[] = $bots; //here you can add elements to the array
}
}
在你的情况下,如果循环至少没有执行一次,变量$all_bots
将是未定义的
修改强>
在循环之后,要处理数组为空时的情况,请执行以下操作:
//if there is some element in all_bots...
if ( ! empty( $all_bots ) )
{
# count values of strings in array
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}
//handle the case the variable all_bots is empty
else
{
$bots = 0;
$count_bots = 0;
$bot_keys = 0;
$mostOccuring = 0;
}
<强> EDIT2 强>
您的回报中的变量未定义,因为当所有$all_bots
为空时,它们都未设置。检查上面的编辑,我已将它们添加到if语句中。但是你必须根据你的需要在你的应用程序中处理这种情况,这样想:$all_bots
为空时这些变量应包含哪些内容?然后将值分配给if语句中的变量
答案 1 :(得分:2)
这种情况正在发生,因为在更改域后,它不会在循环内执行。试试 -
$all_bots= array(); // Define an empty array
foreach($array_sp_bots as $bots){
if(strpos($bots, "bot")){
$all_bots[] = $bots;
}
}
# count values of strings in array
$bots = array_count_values($all_bots);
如果$array_sp_bots
为空,那么它将不执行循环&amp; $all_bots
将无法定义。对于这种情况,计数将是0
。
或者可能想要为此添加一些检查 -
if(empty($all_bots)) {
// Some error message
} else {
# count values of strings in array
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}