PHP在Foreach循环中有一个"内置"迭代器吗?

Gol*_*a11 11 php foreach iterator phpexcel

我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以很容易地实现类似$c = 0outsite foreach的东西,然后每次循环运行时只增加它,但是有更清洁的东西吗?

tub*_*035 6

PHP的foreach没有内置的这个功能(根据手册).使用for循环来拥有迭代器或自己实现它.


Ale*_*cki 5

for循环会给你一个自动计数,但没有办法循环的$_REQUEST关联数组.该foreach循环将让你通过循环,但没有内置计数器.这是一个权衡,但至少它是一个非常易于管理的(只需要2行代码来构建计数器)!