在 php foreach 中增加一个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11048173/
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
Increment a value inside php foreach?
提问by gopivignesh.m
Is it possible to increment a php variable inside a foreach? I know how to loop by declaring outside.
是否可以在 foreach 中增加 php 变量?我知道如何通过在外面声明来循环。
I'm looking for something like the syntax below
我正在寻找类似下面的语法
foreach ($some as $somekey=>$someval; $i++)
{
}
回答by Ananth
No, you will have to use
不,你将不得不使用
$i = 0;
foreach ($some as $somekey=>$someval) {
//xyz
$i++;
}
回答by Zoltan Toth
foreach ($some as $somekey=>$someval)
{
$i++;
}
回答by Matas Lesinskas
lazy way of doing is:
懒惰的做法是:
{
$i=1;
foreach( $rows as $row){
$i+=1;
}
}
,but you have to scope foreach for $i to dont exist after foreach or at last unset it
,但你必须为 $i 设置 foreach 的范围,在 foreach 或最后取消它之后不存在
$i=1;
foreach( $rows as $row){
$i+=1;
}
unset($i);
, but you should use for cycle for that as leopold wrote.
,但你应该像 leopold 写的那样使用 for cycle 。
回答by Majid Mushtaq
$dataArray = array();
$i = 0;
foreach($_POST as $key => $data) {
if (!empty($data['features'])) {
$dataArray[$i]['feature'] = $data['features'];
$dataArray[$i]['top_id'] = $data['top_id'];
$dataArray[$i]['pro_id'] = $data['pro_id'];
}
$i++;
}
回答by leopold
I know it is an old one here, but these are my thoughts to it.
我知道这里是旧的,但这些是我的想法。
$some = ['foo', 'bar'];
for($i = 0; $i < count($some); $i++){
echo $some[$i];
}
-- Update--
--更新--
$some = ['foo', 'bar'];
$someCounted = count($some);
for($i = 0; $i < $someCounted; $i++){
echo $some[$i];
}
It would achieve, what you are looking for in first place.
Yet you'd have to increment your index $i.
So it would not save you any typing.
它将实现您首先要寻找的东西。
但是你必须增加你的索引 $i。
所以它不会为你节省任何打字。
回答by axiomer
Is there any reason not to use
有什么理由不使用
foreach ($some as $somekey=>$someval)
{
$i++;
}
?
?
回答by Nadir Sampaoli
foreach ($some as $somekey=>$someval)
{
$i++;
}
回答by YYZ
foreach ($some as $somekey=>$someval)
{
$i++;
}
i is just a variable. Even though it's used to iterate over whatever item you're using, it can still be modified like any other.
i 只是一个变量。即使它用于迭代您正在使用的任何项目,它仍然可以像其他任何项目一样进行修改。
回答by minethisis
This will do the trick! Remember that you'll have to define $i = 0 before the foreach loop if you want to start counting/incrementing from 0.
这将奏效!请记住,如果您想从 0 开始计数/递增,则必须在 foreach 循环之前定义 $i = 0。
$i = 0;
foreach ($some as $somekey=>$someval) {
$i++;
}

