我想通过点分隔键删除特定的子数组。这是一些有效的代码(是的,它有效,但还远未达到好的解决方案):
$Data = [
'one',
'two',
'three' => [
'four' => [
'five' => 'six', // <- I want to remove this one
'seven' => [
'eight' => 'nine'
]
]
]
];
# My key
$key = 'three.four.five';
$keys = explode('.', $key);
$str = "";
foreach ($keys as $k) {
$sq = "'";
if (is_numeric($k)) {
$sq = "";
}
$str .= "[" . $sq . $k . $sq . "]";
}
$cmd = "unset(\$Data{$str});";
eval($cmd); // <- i'd like to get rid of this evil shit
对此有更好的解决方案吗?
最佳答案
您可以使用对数组内元素的引用,然后删除 $keys
数组的最后一个键。
您应该添加一些错误处理/检查键是否确实存在,但这是基础:
$Data = [
'one',
'two',
'three' => [
'four' => [
'five' => 'six', // <- I want to remove this one
'seven' => [
'eight' => 'nine'
]
]
]
];
# My key
$key = 'three.four.five';
$keys = explode('.', $key);
$arr = &$Data;
while (count($keys)) {
# Get a reference to the inner element
$arr = &$arr[array_shift($keys)];
# Remove the most inner key
if (count($keys) === 1) {
unset($arr[$keys[0]]);
break;
}
}
var_dump($Data);
关于php - 通过点分隔键删除多维数组中的子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46318228/