gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:31:52 32 4
gpt4 key购买 nike

我有一个这样的数组:

$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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com