如何将foreach更改为for循环?

时间:2022-07-14 21:35:40

I've read on a web page, explaining that in PHP it is must faster execution to do a for loop than a foreach. This is new to me, but I would like to test this for himself. How do I convert a foreach into a for loop in PHP? Using the one below as an example:

我在一个网页上读过,解释说在PHP中,执行for循环必须比foreach更快。这对我来说是新的,但我想亲自测试一下。如何在PHP中将foreach转换为for循环?以下面的例子为例:

foreach ($station->ITEMS->ITEM as $trips=>$trip) {
    $ny_trips[$trips] = $trip;
}

I've seen for loops in PHP, but not using 'as' in them. So I'm not sure how the above would look in PHP as a for loop. Would it also require doing a count() of $station->ITEMS->ITEM? Thanks!

我在PHP中看过for循环,但在其中没有使用'as'。所以我不确定上面的PHP在for循环中的表现如何。它还需要对$ station-> ITEMS-> ITEM进行count()吗?谢谢!

2 个解决方案

#1


2  

Assuimg the keys on the array are a perfect numerical sequence starting at 0 then this is what you are looking for.

确定数组上的键是一个完整的数字序列,从0开始,这就是你要找的东西。

for($x = 0, $nItems = count($station->ITEMS->ITEM); $x<$nItems; $x++) {
    $ny_trips[$x] = $station->ITEMS->ITEM[$x];
}

If the keys are non-numeric then or not in perfect order then you need to do something like this.

如果键是非数字的,那么或者不是完美的顺序,那么你需要做这样的事情。

$keys = array_keys($station->ITEMS->ITEM);
for($x = 0, $nItems =  count($station->ITEMS->ITEM);$x < $nItems; $x++) {
    $ny_trips[$keys[$x]] = $station->ITEMS->ITEM[$keys[$x]];
}    

#2


0  

for($i=0;$i < count($station->ITEMS->ITEM);$i++){
   $ny_trips[$i] = $station->ITEMS->ITEM[$i];
}

#1


2  

Assuimg the keys on the array are a perfect numerical sequence starting at 0 then this is what you are looking for.

确定数组上的键是一个完整的数字序列,从0开始,这就是你要找的东西。

for($x = 0, $nItems = count($station->ITEMS->ITEM); $x<$nItems; $x++) {
    $ny_trips[$x] = $station->ITEMS->ITEM[$x];
}

If the keys are non-numeric then or not in perfect order then you need to do something like this.

如果键是非数字的,那么或者不是完美的顺序,那么你需要做这样的事情。

$keys = array_keys($station->ITEMS->ITEM);
for($x = 0, $nItems =  count($station->ITEMS->ITEM);$x < $nItems; $x++) {
    $ny_trips[$keys[$x]] = $station->ITEMS->ITEM[$keys[$x]];
}    

#2


0  

for($i=0;$i < count($station->ITEMS->ITEM);$i++){
   $ny_trips[$i] = $station->ITEMS->ITEM[$i];
}