【问题标题】:converting a PHP for loop to a for each [closed]将 PHP for 循环转换为 for each [关闭]
【发布时间】:2020-09-03 06:58:50
【问题描述】:

我对算法不太熟悉,请有人帮我将此 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;
    }
}

【问题讨论】:

  • 这里出现的第一个问题是:为什么?

标签: php algorithm for-loop foreach


【解决方案1】:
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;             
       }
}

【讨论】:

  • 将其设为$cartBookItems as $currentCartBookItem 以进一步简化。
  • @castis 感谢更新:)
【解决方案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;
    }
}

【讨论】:

  • $cartBookItems as $currentCartBookItem 将需要更少的代码更改。
猜你喜欢
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
相关资源
最近更新 更多