dongpu9852 2013-03-18 19:34
浏览 6
已采纳

如何以编程方式构建数组/对象调用[关闭]

I'm developing a Drupal module that allows users to use a superglobal variable as a filter in their view. They need to be able to enter into a field the variable they want to use, and then my function needs to then go and retrive the value of that variable. This is easy enough if you only allow one level, and only array. But I would like to allow for multiple levels, and even better, allow them to access objects and/or arrays.

So if the user were to choose SESSION, and then enter: ['anarray']['anotherlevel']['something']

my function would then get the value of: $_SESSION['anarray']['anotherlevel']['something']

Even better would be if the user could enter something like: ['anarray']->anotherlevel->something['morethings']

my function would get the variable of: $_SESSION['anarray']->anotherlevel->something['morethings']

And so on. For even cleaner code, if they could just use + and - to represent an array and object respectively, that would be even better. So the last example would be entered as: +anarray-anotherlevel-something+morethings

Any ideas?

  • 写回答

2条回答 默认 最新

  • douxiza9868 2013-03-18 19:41
    关注
    $path = 'foo.bar.baz';
    
    $value = $_SESSION;
    
    foreach (explode('.', $path) as $key) {
        if (is_array($value) && array_key_exists($key, $value)) {
            $value = $value[$key];
        } else if (is_object($value) && property_exists($value, $key)) {
            $value = $value->$key;
        } else {
            throw new InvalidArgumentException(sprintf('The path %s does not exist', $path));
        }
    }
    
    echo $value;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果