Mic*_*ski 26
这是一个复杂的方法,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']
}
Run Code Online (Sandbox Code Playgroud)
只是简单地预测一切:
foreach ($input_array as $key => $val) {
if (is_int($key)) {
// do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
编辑误读原始帖子,并认为我看到"数字"而不是"整数"键.更新使用is_int()
而不是is_numeric()
.
Eht*_*ham 11
foreach($array as $key => $val) {
if(!is_int($key))
continue;
// rest of the logic
}
Run Code Online (Sandbox Code Playgroud)
这个单行返回一个包含值及其数字键的新数组:
$new_array = array_filter($my_array, 'is_int', ARRAY_FILTER_USE_KEY);
Run Code Online (Sandbox Code Playgroud)
所以如果我们有这个:
array(
'fruit' => 'banana'
1 => 'papaya'
)
Run Code Online (Sandbox Code Playgroud)
..我们得到了这个:
array(
1 => 'papaya'
)
Run Code Online (Sandbox Code Playgroud)