PHP中是否有一个函数可以从数组的特定索引开始计数?
示例:
$array = array(1, 2, 3, 4, 'string', 5, 6, 7);
var_dump(count($array)); // 8 items
功能类似于我需要的:
$array = array(1, 2, 3, 4, 'string', 5, 6, 7);
var_dump(countFromIndex($array, 2)); // 6 items (started from 3)
不,您需要编写一个。最简单的(不是最好的,只是我能从脑海中提取的)方法是类似的方法
function countFrom($array, $indexFrom) {
$counter = 0;
$start = false;
foreach ($array as $k=>$v) {
if ($k == $indexFrom) {
$start = true;
}
if ($start) {
$counter ++;
}
}
return $counter;
}
或者,也许内存占用较少:
function countFrom($array, $indexFrom) {
$start = false;
$counter = 0; // experiment to see if this should be 0 or 1
foreach ($array as $k=>$v) {
if ($k == $indexFrom) {
$new = array_splice($array, $counter);
return count($new);
}
$counter ++;
}
如果您试图获取从索引号2开始的项目数,您可以简单地使用count($array) - 2
?
类似这样的东西:
function countFromIndex($array, $index)
{
$values = array_values($array);
$count = count($values);
$search = 0;
for($i=0; $i<$count; $i++)
{
$search++;
if($values[$i] === $index) break;
}
return $count-$search;
}
$array = array(1, 2, 3, 4, 'string', 5, 6, 7);
var_dump(countFromIndex($array, 2)); // 6 items (started from 3)
var_dump(countFromIndex($array, 'string')); // 3 items (started from 5)
var_dump(countFromIndex($array, 7)); // 0 items (started from ?)
$total = count($array);
$count = 0;
for($i = 2; $i < $total; $i++)
{
$count++;
}
更改$i = 2
以设置起点。