我使用foreach循环遍历请求数组,因为我希望有一种简单的方法来利用请求数组的键和值。
但是,我还希望有一个循环运行次数的数字索引,因为我正在用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
outsite the foreach这样的东西,然后在每次循环运行时递增它,但是有没有更干净的东西呢?
发布于 2012-08-13 14:39:52
PHP的foreach没有内置这个功能(per the manual)。使用for loop来创建迭代器,或者自己实现它。
发布于 2012-08-13 14:39:11
for
循环将为您提供一个自动计数器,但无法遍历您的$_REQUEST
关联数组。foreach
循环将允许您循环,但没有内置计数器。这是一种权衡,但至少它是一个非常容易管理的(只需要2行代码就可以构建计数器)!
发布于 2012-08-13 14:48:32
使用SPL Iterator Class。我相信这里面一定有你可以利用的东西。
https://stackoverflow.com/questions/11936492
复制