仅在数组中定位数字键

hen*_*ijs 16 php arrays

我有一个包含2种键,字符串和整数的数组.我想foreach()在这个数组上做,并希望只为数字键做.这样做最优雅的方式是什么?

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().

  • `array_filter` 中的匿名函数可以替换为字符串 `'is_int'` :) (2认同)

Eht*_*ham 11

    foreach($array as $key => $val) {
        if(!is_int($key))
             continue;
        // rest of the logic
    }
Run Code Online (Sandbox Code Playgroud)

  • 实际上,没关系.[PHP始终将数字键存储为整数.](http://stackoverflow.com/questions/4100488/a-numeric-string-as-array-key-in-php/4100765#4100765) (2认同)

Ign*_*ura 5

这个单行返回一个包含值及其数字键的新数组:

$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)