仅在数组中定位数字键
我有一个包含2种键,字符串和整数的数组。我想在这个数组上做,并且只想对数字键做。最优雅的方法是什么?foreach()
我有一个包含2种键,字符串和整数的数组。我想在这个数组上做,并且只想对数字键做。最优雅的方法是什么?foreach()
下面是一个复杂的方法,用于返回数字键,然后循环访问它们。array_filter()
// $input_array is your original array with numeric and string keys
// array_filter() returns an array of the numeric keys
// Use an anonymous function if logic beyond a simple built-in filtering function is needed
$numerickeys = array_filter(array_keys($input_array), function($k) {return is_int($k);});
// But in this simple case where the filter function is a plain
// built-in function requiring one argument, it can be passed as a string:
// Really, this is all that's needed:
$numerickeys = array_filter(array_keys($input_array), 'is_int');
foreach ($numerickeys as $key) {
// do something with $input_array[$key']
}
不过,仅仅提前完成所有事情要容易得多:
foreach ($input_array as $key => $val) {
if (is_int($key)) {
// do stuff
}
}
编辑误读了原始帖子,以为我看到的是“数字”而不是“整数”键。更新为使用而不是 .is_int()
is_numeric()
foreach($array as $key => $val) {
if(!is_int($key))
continue;
// rest of the logic
}