[英]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.