由于"value of type null",函数返回的子数组有时无法使用

Sub-array returned by function sometimes cannot be used due to "value of type null"

以下 PHP 代码从烤箱数组中随机选择一个烤箱。如果选定的烤箱没有通过任何过滤器,它将从数组中删除,函数递归执行自身,直到找到合格的烤箱。将找到的合格烤箱子数组返回显示为特色烤箱。

可能还有其他种类的电器(例如冰箱、搅拌机、洗碗机等)也需要随机展示其产品。这样就创建了可重用的 $get_featured_product 函数。

每种电器的数组元素个数可以增加

$get_featured_product = function ($products) use (&$get_featured_product)
{
    $rand_key = array_rand($products);
    if ($products[$rand_key]['rating'] < 7 || $products[$rand_key]['discount'] < 30 || $products[$rand_key]['deal'] != 'On Sale')
    {
        unset($products[$rand_key]);
        $get_featured_product($products);
    }
    else
    {
        return $products[$rand_key];
    }
};

$ovens = array(
    array(
        'name' => 'Wonderful Oven',
        'rating' => 5.0,
        'discount' => 10,
        'deal' => 'Free Shipping'
    ),
    array(
        'name' => 'Greatest Oven',
        'rating' => 7.3,
        'discount' => 40,
        'deal' => 'On Sale'
    ),
    array(
        'name' => 'Fantastic Oven',
        'rating' => 4.7,
        'discount' => 60,
        'deal' => 'Clearance'
    ),
    array(
        'name' => 'Remarkable Oven',
        'rating' => 8.6,
        'discount' => 30,
        'deal' => 'On Sale'
    ),
    array(
        'name' => 'Incredible Oven',
        'rating' => 3.2,
        'discount' => 20,
        'deal' => 'Black Friday'
    ),
    array(
        'name' => 'Superb Oven',
        'rating' => 6.3,
        'discount' => 50,
        'deal' => 'Clearance'
    )
);

$featured_oven = $get_featured_product($ovens);
echo "Featured Oven: {$featured_oven['name']} (Rating: {$featured_oven['rating']}; Discount: {$featured_oven['discount']}% OFF)";

我遇到的问题是,有时由于以下通知导致代码失败:

Notice: Trying to access array offset on value of type null in php_file_path

但数组确实包含合格的烤箱,因此返回的子数组应该可以工作。我不明白为什么会有 is/are 个空值。

注:我之前问过类似的问题。但是代码被我过度简化了,不能真正反映我遇到的问题。对于那个很抱歉。这次,我相信问题确实反映了问题。

您的病情 return 什么都没有:

if (...)
{
    unset($products[$rand_key]);
    $get_featured_product($products);
    // ^ add a return here
}
else
{
    return $products[$rand_key];
}