php - 如何使用字符串从嵌套数组中获取值

标签 php arrays string multidimensional-array

我有一个这样的数组:

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

我有一个这样的字符串:
$address = '123_456_789';

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

有什么方法可以实现这一点,使用它是一种好习惯吗?

最佳答案

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

<?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,"_");
?>

关于php - 如何使用字符串从嵌套数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33264853/

相关文章:

php - 如何在ssh中使用pid查看正在运行的后台任务

python - 如何计算列表中值 block 的大小?

python - 用 Python 交换字符串中每对相邻字符的最简单方法是什么?

arrays - 检查数组中的一个元素是否包含在字符串中

arrays - 在数组中查找峰值元素的最佳算法

python - 检查字符串是否以列表中的一个字符串结尾

java - Java中如何分割字符串?

php - 同一用户登录具有不同数据库的不同 WordPress 域

php - 使用两个不同的数组构建一个 MySQL INSERT,每个数组使用

php - 更正 HTML 状态代码以防止未经授权的访问和禁止的访问。 (使用 Ajax )