如何使用字符串从嵌套数组中获取值 [英] How to get value from nested array using string

查看:57
本文介绍了如何使用字符串从嵌套数组中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

$temp = array( '123' => array( '456' => array( '789' => '0' ) ),
               'abc' => array( 'def' => array( 'ghi' => 'jkl' ) )
             );

我有一个这样的字符串:

I have a string like this:

$address = '123_456_789';

我可以使用上面的数组 $temp 和字符串 $ 获取 $temp['123']['456']['789'] 的值吗地址?

Can I get value of $temp['123']['456']['789'] using above array $temp and string $address?

有什么方法可以实现这一点吗?使用它是一种很好的做法吗?

Is there any way to achieve this and is it good practice to use it?

推荐答案

这是一个简单的函数,它接受一个数组和一个字符串地址,其中的键由任何定义的定界符分隔.通过这种方法,我们可以使用 for 循环来迭代到所需的数组深度,如下所示.

This is a simple function that accepts an array and a string address where the keys are separated by any defined delimiter. With this approach, we can use a for-loop to iterate to the desired depth of the array, as shown below.

<?php
function delimitArray($array, $address, $delimiter="_") {
    $address = explode($delimiter, $address);
    $num_args = count($address);

    $val = $array;
    for ( $i = 0; $i < $num_args; $i++ ) {
        // every iteration brings us closer to the truth
        $val = $val[$address[$i]];
        }
    return $val;
    }

$temp = array("123"=>array("456"=>array("789"=>"hello world")));
$address = "123_456_789";
echo delimitArray($temp,$address,"_");
?>

这篇关于如何使用字符串从嵌套数组中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆