doujianqin5172 2014-08-04 20:08
浏览 90
已采纳

解析字符串以获取数组元素[重复]

This question already has an answer here:

I'm trying to figure out how to take a string, parse it, and get the corresponding array values that match the parsed keys back. I don't know how to properly explain this, so here's an example.

$testArray = array(
    'router' => array(
        'format' => 'xml',
    ),
);

The string I want to parse will look like this - router.format, and I'm obviously expecting back xml as a string. The passed in string can have any arbitrary amount of separating periods. I was thinking of doing recursion somehow, but I can't think of any way in which this will work.

This is very similar to SF2's service container and the way in which you get services back.

Any help would be great!

</div>
  • 写回答

4条回答 默认 最新

  • douzuan2814 2014-08-04 20:19
    关注

    Might need some error checking:

    $testArray = array(
        'router' => array(
            'format' => 'xml',
        ),
    );
    $path = 'router.format';
    
    $result = $testArray;
    foreach(explode('.', $path) as $key) {
        if(isset($result[$key])) {
            $result = $result[$key];
        }
    }
    print_r($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?