我对算法不太熟悉,有人可以帮我把这个 for 循环转换为 foreach 吗
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;
}
}
UPDATE
感谢@castis 的建议。你可以直接拥有$currentCartBookItem
当你循环可迭代变量时。
foreach($cartBookItems as $currentCartBookItem ) {
if($currentCartBookItem->getBookID() == $book->getId()) {
$newQuantity = $currentCartBookItem->getQuantity() + $quantity;
$currentCartBookItem->setQuantity($newQuantity);
$isItemAlreadyExists = true;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)