PHP foreach循环中的自动递增数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1988902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto incrementing number in PHP foreach loop
提问by a1anm
This is the beginning of a php for loop. I would like to edit it so that 'INSERT NUMBER HERE' gets replaced with an incrementing number. Ie. first loop it would be 1, then 2, then 3 etc.
这是 php for 循环的开始。我想对其进行编辑,以便将“在此处插入数字”替换为递增的数字。IE。第一个循环是 1,然后是 2,然后是 3 等等。
<?php foreach ($_productCollection as $_product): ?>
<div style="float: left; font-size: 120px;height:50px;padding-top:50px; color:#ccc">INSERT NUMBER HERE</div>
<div class="listing-item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
How can I achieve this?
我怎样才能做到这一点?
Thanks
谢谢
回答by dfilkovi
<?php
$n = 0;
foreach ($_productCollection as $_product):
$n++;
?>
<div style="float: left; font-size: 120px;height:50px;padding-top:50px; color:#ccc"><?php echo $n; ?>
</div>
<div class="listing-item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
回答by Ignacio Vazquez-Abrams
You could use array_keys()to get an indexed array from an associative array, at which point foreachwill yield the index as the new key, and the old key as the new value. Indexing the old array with the new value will give you the old value, and the new key will be a counter for elements in the array.
您可以使用array_keys()从关联数组中获取索引数组,此时foreach将索引作为新键,旧键作为新值。用新值索引旧数组将为您提供旧值,而新键将是数组中元素的计数器。

