dongzizhi9903 2011-01-30 14:32
浏览 46
已采纳

使用函数参数访问更深的数组键

I am trying to create a function (unless one already exists?) which is supposed to accept an "unlimited" amount of arguments (using func_get_args()) to find the value of an array key. Regardless of how deep within the array it is to be found.

Say if I would use $registry->getSetting( 'template', 'default' ); I am supposed to get the value of $this->properties['settings']['template']['default'] or if I would you $registry->getSetting( 'users', 1, 'name', 'first' ); I would expect it to return the value of $this->properties['users'][1]['name']['first'] (just a second example with a couple of extra arguments).

Now, to do something like this, I could count the amount of arguments passed using func_num_args() and then do a switch with different cases. Although, this would limit it to a certain amount of keys.

So I am asking you if there is a way of doing this, to allow an "unlimited" amount rather than a fixed amount of arguments to access a deeper key of an array.

<?PHP
class Registry
{
    // Values are actually fetched from a config file, but for easier understanding
    private $properties = array(
        'settings' => array(
            'template' => array(
                'default' => 'default',
                'caching' => TRUE
            )
        )
    );

    public function getSetting( )
    {
        // do something like
        // return $this->properties['settings'][func_get_args( )];
    }
}
?>

Any help whatsoever is highly appreciated.
Thank you!

  • 写回答

5条回答 默认 最新

  • dongxiaowei_1234 2011-01-30 14:43
    关注
    <?PHP
    class Registry
    {
        // Values are actually fetched from a config file, but for easier understanding
        private $properties = array(
            'settings' => array(
                'template' => array(
                    'default' => 'default',
                    'caching' => TRUE
                )
            )
        );
    
        public function getSetting()
        {
            $result = $this->properties;
    
            foreach (func_get_args() as $arg) {
                if (isset($result[$arg])) {
                    $result = $result[$arg];
                } else {
                    return;
                }
            }
    
            return $result;
        }
    }
    
    $r = new Registry();
    
    var_dump($r->getSetting('settings', 'template', 'default'));
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图