有没有更好的方法来创建数组键,以避免丢失索引通知


Is there a better way to create array keys to avoid missing index notice?

我正在循环处理一堆数据,我似乎在做一些感觉有点重复的事情。

if(!isset($productitems[$stop->route_id])){
    $productitems[$stop->route_id] = [];
}
if(!isset($productitems[$stop->route_id][$location_id])){
    $productitems[$stop->route_id][$location_id] = [];
}
if(!isset($productitems[$stop->route_id][$location_id][$week])){
    $productitems[$stop->route_id][$location_id][$week] = [];
}
if(!isset($productitems[$stop->route_id][$location_id][$week][$day])){
    $productitems[$stop->route_id][$location_id][$week][$day] = [];
}
if(!isset($productitems[$stop->route_id][$location_id][$week][$day][$task->product_id])){
    $productitems[$stop->route_id][$location_id][$week][$day][$task->product_id] = [];
}
if(!isset($productitems[$stop->route_id][$location_id][$week][$day][$task->product_id][(int)$task->refill_id])){
    $productitems[$stop->route_id][$location_id][$week][$day][$task->product_id][(int)$task->refill_id] = 0;
}

有没有一种不同的方法可以在不进行所有isset检查的情况下填充这些多维数组?

edit我知道只在php中设置$productitems[$stop->route_id][$location_id][$week][$day][$task->product_id][(int)$task->refill_id]是可能的,但是php会记录一个警告,并且我正在处理的项目使用Laravel,这将引发异常。

PHP会自动创建不存在的子键(您可以通过检查isset来避免通知)。如果你愿意,可以随意创建一个函数来为你做这件事(最大限度地减少变量的双重粘贴。

代码

<?php
    error_reporting(E_ALL);
    function setDefault(&$variable, $default) {
        if (!isset($variable)) {
            $variable = $default;
        }
    }
    $foo = array(
        'foo' => 'oof'
    );
    setDefault($foo['sub']['arrays']['are']['pretty']['cool'], 0);
    print_r($foo);
?>

输出

Array
(
    [foo] => oof
    [sub] => Array
        (
            [arrays] => Array
                (
                    [are] => Array
                        (
                            [pretty] => Array
                                (
                                    [cool] => 0
                                )
                        )
                )
        )
)

演示

3v4l显示,从4.3.0到5.5.6的任何PHP版本中都没有任何通知,而这个显然会发出通知。

如果你不想使用函数,可以随意使用代码中的最后一个if条件:

<?php
    error_reporting(E_ALL);
    $foo = array(
        'foo' => 'oof'
    );
    if (!isset($foo['sub']['arrays']['are']['pretty']['cool'])) {
        $foo['sub']['arrays']['are']['pretty']['cool'] = 0;
    }
    print_r($foo);
?>

3v4l演示

php不需要声明所有内容,所以我认为您不需要这些。我只是在命令提示符下在本地机器上尝试了一下,这是输出。。。

代码:

<?php
    $productitems['a']['b']['c']['d']['e']['f'] = 65;
    var_dump($productitems);
?>

输出:

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      array(1) {
        ["d"]=>
        array(1) {
          ["e"]=>
          array(1) {
            ["f"]=>
            int(65)
          }
        }
      }
    }
  }
}