【问题标题】:unset array keys if key is string如果键是字符串,则取消设置数组键
【发布时间】:2015-12-26 22:45:26
【问题描述】:

我有类似这样的数组

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

但可以在不指定确切名称的情况下找到键,因为我只想要数字键。

【问题讨论】:

  • $arr = array_filter($arr, function ($key) {return is_numeric($key); }, ARRAY_FILTER_USE_KEY ); 如果你运行的是 PHP >= 5.6.0
  • 但是您是从数据库中获取这个数组吗?如果是这样,你可以告诉你的 fetch 只返回一个枚举数组

标签: php arrays unset


【解决方案1】:

解决方案是:

假设你知道它只有 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);

为什么会生成这样的数组?

【讨论】:

  • pdo 像这个数组一样生成,我在转换为 json 时需要隐藏表名
【解决方案2】:

编辑:阅读 Valdorous 的答案后意识到它是多维数组。以下应递归处理多维数组。

调用函数(见下文)

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/en/function.is-numeric.php

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 2012-05-13
    • 2013-06-05
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多