简体   繁体   English

使用功能访问多维数组的元素

[英]Access to elements of a multidimensional array, with a function

I need a function with variable number of arguments, to access to the elements of a multidimensional array. 我需要一个具有可变数量参数的函数,以访问多维数组的元素。 I have done in this way ($this->_config is the array)... 我已经用这种方式完成了($ this-> _ config是数组)...

function item()
{
    if(func_num_args() != 0){
        $config = $this->_config;
        $args = func_get_args();
        foreach($args as $item){
            $config = $config[$item];
        }
        unset($args);
        return $config;
    }
    else throw new Exception('An item index is required.');
}

Is there a way to do better? 有办法做得更好吗? Thanks to all! 谢谢大家!

In your question you say you have a multidimensional array, so I take it is like this: 在您的问题中,您说您有一个多维数组,所以我认为是这样的:

$config = array('foo' => array('bar' => array('baz' => 3)));

Calling item('foo', 'bar', 'baz') would run all the way through to the last array and return 3. If that is what you want, you could just write $config['foo']['bar']['baz'] or place your configs in an ArrayObject and use either the array access notation or $config->foo->bar->baz (though all nested arrays must be ArrayObjects too then). 调用item('foo', 'bar', 'baz')会一直运行到最后一个数组并返回3。如果这是您想要的,则只需编写$config['foo']['bar']['baz']或将您的配置放置在ArrayObject中,并使用数组访问符号或$config->foo->bar->baz (尽管那时所有嵌套数组也必须也是ArrayObjects)。

If you want to keep the function, you should add some checking on the index before you grab it, because PHP will raise a Notice about undefined indexes. 如果要保留该函数,则应在获取索引之前对其进行一些检查,因为PHP会引发有关未定义索引的声明。 In addition, why not use InvalidArgumentException instead of Exception. 此外,为什么不使用InvalidArgumentException而不是Exception。 Fits better for this case. 更适合这种情况。

edit: removed some portion of the answer, because it was more like loud thinking 编辑:删除了部分答案,因为它更像是大声思考

edit after comments 评论后编辑
Tbh, I find it a rather awkward approach to reinvent array access through a method like this. TBH,我发现通过这样的方法来重塑数组访问是一种相当尴尬的方法。 In my opinion you should either pass the entire config or a subset to your objects during construction and let them take whatever they need through the regular array accessors. 我认为您应该在构造过程中将整个配置或子集传递给对象,并让它们通过常规数组访问器获取所需的内容。 This will decouple your objects from your configManager and allows for easier modification at a later point. 这将使您的对象与configManager 脱钩,并允许以后进行更轻松的修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM