将PHP for循环转换为for

时间:2018-07-30 13:59:02

标签: php algorithm for-loop foreach

我对算法不太适应,有人可以帮我将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;
    }
}

2 个答案:

答案 0 :(得分:4)

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

foreach($cartBookItems as $currentCartBookItem ) {
       if($currentCartBookItem->getBookID() == $book->getId()) {
             $newQuantity = $currentCartBookItem->getQuantity() + $quantity;
             $currentCartBookItem->setQuantity($newQuantity);
             $isItemAlreadyExists = true;             
       }
}

答案 1 :(得分:2)

foreach($cartBookItems as $bookItem) {
    $currentCartBookItem = $bookItem;
    if($currentCartBookItem->getBookID() == $book->getId()) {
        $newQuantity = $currentCartBookItem->getQuantity() + $quantity;
        $currentCartBookItem->setQuantity($newQuantity);
        $isItemAlreadyExists = true;
    }
}

//or

foreach($cartBookItems as $bookItem) {
    if($bookItem->getBookID() == $book->getId()) {
        $newQuantity = $bookItem->getQuantity() + $quantity;
        $bookItem->setQuantity($newQuantity);
        $isItemAlreadyExists = true;
    }
}