我想删除所有键 [Name] ,但主要问题是列表键中的数字([List1],[List2]等)。键[List]上的数字可能更多,但例如我只给了两个。
我想改变它,因为它是一个旧的json文件,而在新版本中它没有密钥,比如转换器
有没有办法遍历整个阵列并删除所有[名称]键?
Array(
[Values] => 1
[List1] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
[Name] => Nm1
)
)
[1]=> Array(
[Properties] => Array(
[Id] => 1
[Name] => Nm1
)
)
)
[List1] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
[Name] => Nm1
)
)
)
)
[List2] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
[Name] => 0
)
)
)
)
)
[List2] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
[Name] => Nm1
)
)
)
[List1] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
[Name] => Nm1
)
)
)
)
)
)
我的目标是:
Array(
[Values] => 1
[List1] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
)
)
[1]=> Array(
[Properties] => Array(
[Id] => 1
)
)
)
[List1] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
)
)
)
)
[List2] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
)
)
)
)
)
[List2] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
)
)
)
[List1] => Array(
[Product1] => Array(
[0] => Array(
[Properties] => Array(
[Id] => 1
)
)
)
)
)
)
我试过了:
$ProductCount= count($array['List1']['Product1']);
for($i = 0;$i<$ProductCount;$i++){
unset($array['List1']['Product1'][$i][Properties][Name]);
}
但我也有一个键[List2],可以是[List3]等。
答案 0 :(得分:4)
你可以这样做:
function remove_key($array, $key)
{
foreach($array as $k => $v) {
if(is_array($v)) {
$array[$k] = remove_key($v, $key);
} elseif($k == $key) {
unset($array[$k]);
}
}
return $array;
}
$array = remove_key($array, 'Name');
$array
是您的多维数组,$key
是您要删除的键名。
注意:如果键表示一个数组(不是值),此方法将忽略它,但我认为这是您需要的。如果要在密钥匹配时删除数组,则需要在foreach循环中切换条件顺序。