如何使用字符串从嵌套数组中获取值
问题描述:
我有一个像这样的数组:
I have an array like this:
$temp = array( '123' => array( '456' => array( '789' => '0' ) ),
'abc' => array( 'def' => array( 'ghi' => 'jkl' ) )
);
我有这样的字符串:
$address = '123_456_789';
我可以得到 $ temp ['123'] ['456 '] ['789']
使用上面的数组 $ temp
和字符串 $ address
?
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,"_");
?>