gpt4 book ai didi

php - 在数组中设置嵌套项

转载 作者:行者123 更新时间:2023-12-02 22:14:00 24 4
gpt4 key购买 nike

我的功能:

function setItem(array $arr, $item, $value, $delimiter = '.') {
$nodes = explode($delimiter, $item);
$code = "\$arr['".join("']['", $nodes)."'] = \$value;";
eval($code);
return $arr;
}

使用:

$data = array();
$data = setItem($data, 'test.qwerty.sub', 'value');

没有“eval”有什么办法吗?

最佳答案

是的,但它涉及使用引用:

function setItem(array &$arr, $path, $value, $delim = '.'){

$path = explode($delim, $path);

$root = &$arr;

// pointer to the current item
$current = &$arr;

foreach($path as $item){
$current[$item] = array();

// set pointer to the newly created array
$current = &$current[$item];
}

// reached the last path component;
// assign the value to it
$current = $value;

return $root;
}

关于php - 在数组中设置嵌套项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793782/

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