按路径取消多维数组中的元素 [英] Unset element in multi-dimensional array by path
问题描述
我正在尝试删除多维数组中的元素。
I'm trying to remove an element in a multidimensional array.
需要删除的元素由类似 globals.connects.setting1
。这意味着我打算修改这样的数组:
The element which is needs to be removed is given by a string like globals.connects.setting1
. This means I'm intend to modify an array like this:
// Old Array
$old = array(
"globals" => array(
"connects" => array(
"setting1" => "some value",
"setting2" => "some other value",
"logging" => array()),
"someOtherKey" => 1
));
// After modification
$new = array(
"globals" => array(
"connects" => array(
"setting2" => "some other value",
"logging" => array()),
"someOtherKey" => 1
));
不幸的是,我既不知道给定字符串的深度,也不知道数组的确切结构。我正在寻找类似 unsetElement($ path,$ array)
的函数,如果返回,该函数将返回数组 $ new
给出数组 $ old
和 globals.connects.setting1
作为参数。
Unfortunately I do not know either the "depth" of the given string nor the exact structure of the array. I'm looking for a function like unsetElement($path, $array)
which returns the array $new
, if the array $old
and globals.connects.setting1
is given as argument.
出于安全原因,我想避免使用 eval()
函数。
I'd like to avoid the use of the eval()
function due to security reasons.
推荐答案
$testArr = [
"globals" => [
"connects" => [
'setting1' => [
'test' => 'testCon1',
],
'setting2' => [
'abc' => 'testCon2',
],
],
],
'someOtherKey' => [],
];
$pathToUnset = "globals.connects.setting2";
function unsetByPath(&$array, $path) {
$path = explode('.', $path);
$temp = & $array;
foreach($path as $key) {
if(isset($temp[$key])){
if(!($key == end($path))) $temp = &$temp[$key];
} else {
return false; //invalid path
}
}
unset($temp[end($path)]);
}
unsetByPath($testArr, $pathToUnset);
这篇关于按路径取消多维数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!