PHP在Foreach循环中是否有“内置”的迭代器?

15

我正在使用foreach循环遍历REQUEST数组,因为我想要一个简单的方法来利用REQUEST数组的键和值。

然而,我还想要一个数字索引来记录循环运行的次数,因为我正在使用PHPExcel编写电子表格,并且我想要使用SetCellValue函数。我考虑像这样做:

foreach( $_REQUEST as $key => $value){
    $prettyKeys = ucwords(preg_replace($patt_underscore," ",preg_replace($patt_CC,"_",$key)));
    $prettyVals = ucwords(preg_replace($patt_underscore," ",preg_replace($patt_CC,"_",$value)));
    // Replace CamelCase with Underscores, then replace the underscores with spaces and then capitalize string
    // "example_badUsageOfWhatever" ==> "Example Bad Usage Of Whatever"


    $myExcelSheet->getActiveSheet()->SetCellValue( "A". $built-in-foreach-loop-numerical-index ,$prettyKeys);
    $myExcelSheet->getActiveSheet()->SetCellValue( "B". $built-in-foreach-loop-numerical-index ,$prettyVals);
}

我知道我可以轻松地实现类似于$c = 0的东西,在foreach之外,然后每次运行循环时仅增加它,但有没有更简洁的方法?


2
总的来说,不行。就像任何一种编程语言一样,如果你想要一个计数器,你必须自己实现它。 - DaveRandom
1
如果你需要这个功能,请使用for循环。 - Tim
8个回答

7

PHP的foreach循环不具备这种功能(根据手册)。使用for循环来实现迭代器或自己实现该功能。


5
< p > for循环会提供自动计数器,但无法遍历您的$_REQUEST关联数组。 foreach循环可以让您遍历,但没有内置计数器。这是一种折衷方案,但至少它是非常可管理的(仅需要两行代码来构建计数器)!


1

不,没有内置的迭代器数字索引。不过你可以用其他方法解决这个问题。

最明显的方法是使用简单的 for 循环:

for ($i = 0, $numFoo = count($foo); $i < $numFoo; ++$i) {
    // ...
}

您也可以使用带有计数器变量的foreach

$i = 0;
foreach ($foo as $key => $value) {
    // ...
    ++$i;
}

1

使用for循环

你肯定可以使用for循环来实现,只是有点丑陋:

reset($array);
for ($i=0; $i<count($array); $i++) {
    // $i is your counter
    // Extract current key and value
    list($key, $value) = array(key($array), current($array));

    // ...body of the loop...

    // Move to the next array element
    next($array);
}

扩展ArrayIterator

我更倾向于扩展ArrayIterator。添加一个内部计数器,然后覆盖next()和rewind()方法以更新计数器。该计数器给出了当前数组元素的从0开始的键:

class MyArrayIterator extends ArrayIterator
{
    private $numericKey = 0;

    public function getNumericKey()
    {
        return $this->numericKey;
    }

    public function next()
    {
        $this->numericKey++;
        parent::next();
    }

    public function rewind()
    {
        $this->numericKey = 0;
        parent::rewind();
    }
}

// Example:
$it = new MyArrayIterator(array(
    'string key' =>'string value',
    1 =>'Numeric key value',
));
echo '<pre>';
foreach ($it as $key =>$value) {
    print_r(array(
        'numericKey' =>$it->getNumericKey(),
        'key' =>$key,
        'value' =>$value,
    ));
}

// Output:
// Array
// (
//     [numericKey] => 0
//     [key] => string key
//     [value] => string value
// )
// Array
// (
//     [numericKey] => 1
//     [key] => 1
//     [value] => Numeric key value
// )

1
使用SPL迭代器类。我相信在那里面有你可以利用的东西。

你知道学习如何使用这些的好资源吗?我从未见过PHP的那个方面。 - Goldentoa11
我从未找到过,我使用了IteratorIterator、LimitIterator,只能自己摸索。去疯狂地谷歌一下,我相信答案就在那里。 - wesside

0

您可以获取 $_REQUEST 数组中每个键的索引:

$req_index= array_flip (array_keys($_REQUEST));

现在,通过 $req_index[$key],您可以获得当前元素的数字索引,它还提供了循环的迭代次数:

foreach($_REQUEST as $key => $value){
    $prettyKeys = ucwords(preg_replace($patt_underscore," ",preg_replace($patt_CC,"_",$key)));
    $prettyVals = ucwords(preg_replace($patt_underscore," ",preg_replace($patt_CC,"_",$value)));
    // Replace CamelCase with Underscores, then replace the underscores with spaces and then capitalize string
    // "example_badUsageOfWhatever" ==> "Example Bad Usage Of Whatever"

    //THE NUMERICAL INDEX IS $req_index[$key]
    $myExcelSheet->getActiveSheet()->SetCellValue( "A". $req_index[$key], $prettyKeys);
    $myExcelSheet->getActiveSheet()->SetCellValue( "B". $req_index[$key], $prettyVals);
}

0

0
你实际上可以使用foreacharray_values()的组合,这将为数组中的每个元素提供键值。
例如:
$colors = ["red", "blue", "green"];

foreach(array_values($colors) as $key => $color) {
    echo "$color $key";
}
/**Output:
red 0
blue 1
green 2*/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接