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条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)