3

我有一个很奇怪的数组:

Array
(
   [title] => title
   [weight] => 0
   [0] => Text1
   [1] => Text2
   [additional] => Info
}

如何计算哪些键是数字的数组元素(仅)?

4

2 回答 2

9
$data = array(
    'title' => 'title',
    'weight' => 0,
    0 => 'Text1',
    1 => 'Text2',
    'additional' => 'Info'
);

$keyCount = count(
    array_filter(
        array_keys($data),
        'is_numeric'
    )
);

var_dump($keyCount);

编辑

从 PHP 5.6.0 版开始,您可以使用

$keyCount = count(
    array_filter($data, 'is_numeric', ARRAY_FILTER_USE_KEY)
);
于 2013-02-03T21:53:15.393 回答
2

应该很简单:

$i = 0;
foreach  ($arr as $k => $v) {
    if (is_numeric($k))
        $i++;
}
于 2013-02-03T21:50:52.217 回答