为什么 PHP 告诉我这个变量没有定义?

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

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

      $sp_bots = shell_exec("grep bot | awk '{print }' /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 中:

return view('/domains/data', [

       'count_bots' => $count_bots,
        'bot_keys' => $bot_keys,
        'mostOccuring' => $mostOccuring,
    ]);

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

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

$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

您的 return 中有未定义的变量,因为当所有 $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);

如果 $array_sp_bots 为空则不会执行循环并且 $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);
}