[英]unset array keys if key is string
我有这样的数组
$arr =
['0' =>
['0' => 'zero',
'1' => 'test',
'2' =>'testphp',
'test'=>'zero',
'test1'=>'test',
'test2'=>'testphp'],
'1' =>
['0' => 'z',
'1' => 'x',
'2' =>'c',
'test'=>'z',
'test1'=>'x',
'test2'=>'c']
];
和0,1,2与test,test1,test2相同。 我需要删除像test,test1,test2这样的字符串的键。 我知道
foreach($arr as $a){
unset($arr['test']);
unset($arr['test1']);
unset($arr['test2']);
}
但可以在不指定确切名称的情况下找到键,因为我只想要数字键。
一个解决方案是:
假设您知道它只有2层。
$arr =
['0' =>
['0' => 'zero',
'1' => 'test',
'2' =>'testphp',
'test'=>'zero',
'test1'=>'test',
'test2'=>'testphp'],
'1' =>
['0' => 'z',
'1' => 'x',
'2' =>'c',
'test'=>'z',
'test1'=>'x',
'test2'=>'c']
];
foreach($arr as $parentKey=>$arrayItem){
foreach($arrayItem as $key=>$subArrayItem){
if(!is_int($key)){
unset($arr[$parentKey][$key]);
}
}
}
var_dump($arr);
为什么生成了这样的数组?
编辑:阅读了瓦尔多斯的答案后才意识到这是多维数组。 以下应递归处理多维数组。
调用函数(见下文)
remove_non_numeric_keys($arr)
function remove_non_numeric_keys($arr)
{
foreach($arr as $key=>$val)
{
if(!is_numeric($key)) // if not numeric unset it regardless if it is an array or not
{
unset($arr[$key]);
}else{
if(is_array($val) // if it is an array recursively call the function to check the values in it
{
remove_non_numeric_keys($val);
}
}
}
}
这应该只删除非数字键。 http://php.net/manual/zh/function.is-numeric.php
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.