本文介绍了将 PHP for 循环转换为 for each的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对算法不太熟悉,有人可以帮我将这个 for 循环转换为 foreach 吗
Im not soo comfortable in algorithms can somebody please help me to convert this for loop to a foreach please
for($i = 0; $i < count($cartBookItems); $i++) {
$currentCartBookItem = $cartBookItems[$i];
if($currentCartBookItem->getBookID() == $book->getId()) {
$newQuantity = $currentCartBookItem->getQuantity() + $quantity;
$currentCartBookItem->setQuantity($newQuantity);
$isItemAlreadyExists = true;
}
}
推荐答案
foreach($cartBookItems as $each_book_item) {
$currentCartBookItem = $each_book_item;
if($currentCartBookItem->getBookID() == $book->getId()) {
$newQuantity = $currentCartBookItem->getQuantity() + $quantity;
$currentCartBookItem->setQuantity($newQuantity);
$isItemAlreadyExists = true;
}
}
更新
感谢@castis 的建议.您可以在循环迭代变量时直接使用 $currentCartBookItem
.
Thanks to @castis for the suggestion. You can directly have $currentCartBookItem
as you loop iteratable variable.
foreach($cartBookItems as $currentCartBookItem ) {
if($currentCartBookItem->getBookID() == $book->getId()) {
$newQuantity = $currentCartBookItem->getQuantity() + $quantity;
$currentCartBookItem->setQuantity($newQuantity);
$isItemAlreadyExists = true;
}
}
这篇关于将 PHP for 循环转换为 for each的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!