为什么PHP告诉我这个变量是';t定义


Why does PHP tell me this variable isn't defined?

我试图过滤一些日志,就像我需要它们一样,并尝试动态过滤。我有一些域名,我正在尝试从中过滤一些东西,一切都像我想要的那样工作——但现在我更改了域名,现在我的代码不再工作了。它说一个变量没有定义。

      $sp_bots = shell_exec("grep bot | awk '{print $12}' /var/www/laravel/logs/vhosts/domain.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,
    ]);

但是我返回的三个变量都是未定义的。。有人知道为什么吗?

您必须在循环之前将数组初始化为空数组:

$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语句

中的变量

之所以会发生这种情况,是因为在更改域后,它不会在循环中执行。尝试使用-

$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);

如果CCD_ 4为空;则不会定义CCD_ 5。在这种情况下,计数将是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);
}