将PHP for循环转换为for each循环
我对算法不太熟悉有人能帮我把这个for循环转换成foreach吗将PHP for循环转换为for each循环,php,algorithm,for-loop,foreach,Php,Algorithm,For Loop,Foreach,我对算法不太熟悉有人能帮我把这个for循环转换成foreach吗 for($i = 0; $i < count($cartBookItems); $i++) { $currentCartBookItem = $cartBookItems[$i]; if($currentCartBookItem->getBookID() == $book->getId()) { $newQuantity = $currentCartBookItem->get
for($i = 0; $i < count($cartBookItems); $i++) {
$currentCartBookItem = $cartBookItems[$i];
if($currentCartBookItem->getBookID() == $book->getId()) {
$newQuantity = $currentCartBookItem->getQuantity() + $quantity;
$currentCartBookItem->setQuantity($newQuantity);
$isItemAlreadyExists = true;
}
}
for($i=0;$igetBookID()==$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;
}
}
$cartbooksitems作为$currentCartbooksitem
将需要较少的代码更改。将其$cartbooksitems作为$currentCartbooksitem
进一步简化。@castis Thank updated:)Thank alot的效果非常好!!!这里出现的第一个问题是:为什么?
foreach($cartBookItems as $currentCartBookItem ) {
if($currentCartBookItem->getBookID() == $book->getId()) {
$newQuantity = $currentCartBookItem->getQuantity() + $quantity;
$currentCartBookItem->setQuantity($newQuantity);
$isItemAlreadyExists = true;
}
}
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;
}
}