简体   繁体   English

如果key为字符串,则取消设置数组键

[英]unset array keys if key is string

i have array something like this 我有这样的数组

$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']
        ];

and 0,1,2 is this same as test,test1,test2. 和0,1,2与test,test1,test2相同。 I need remove keys where is string like test,test1,test2. 我需要删除像test,test1,test2这样的字符串的键。 I know the way 我知道

foreach($arr as $a){
   unset($arr['test']);
   unset($arr['test1']);
   unset($arr['test2']);
}

but it is possible find keys without specifying the exact name, because i want only number keys. 但可以在不指定确切名称的情况下找到键,因为我只想要数字键。

A solution would be: 一个解决方案是:

Assuming you know it will only have 2 layers. 假设您知道它只有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);

Why is it though that such arrays have been generated? 为什么生成了这样的数组?

edit: after reading Valdorous answer realized it is multidimensional array. 编辑:阅读了瓦尔多斯的答案后才意识到这是多维数组。 the following should handle recursively a multi-dimensional array. 以下应递归处理多维数组。

call the function (see below) 调用函数(见下文)

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);
             }
        }
    }
}

This should remove only non-numeric keys. 这应该只删除非数字键。 http://php.net/manual/en/function.is-numeric.php http://php.net/manual/zh/function.is-numeric.php

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM