简体   繁体   中英

php foreach with if loop through array of objects performing if condition times members in array instead of only once

$_SESSION['quantity'] is an array of Objects.

let's say I already added a product with id = 1 to the array.

Next I add same product with id = 1 , so now $sameProduct = 1 and is set.

$q->update() increments by the property 'quantity' of that object by 1.

The code works well when there is only one item in the array, the problem starts when there are more than one item. The code runs times there items in the array instead of only once for that particular object.

   <?php 
if(!session_start()){session_start();}

require_once 'components/sql_login.php';
require_once 'components/header.php';

if(isset($_SESSION['userSession']) != ""){
    echo "<script> window.location.href = 'user/cart.php'; </script>";
    }

if(!isset($_SESSION['productIds'])){$_SESSION['productIds']=array();}
if(!isset($_SESSION['cartProducts'])){$_SESSION['cartProducts']=array();}
if(!isset($_SESSION['quantity'])){$_SESSION['quantity']=array();}

if (isset($_GET['f'])){ 
    if(!in_array($_GET['f'],$_SESSION['productIds'])){
    $newFairy = $_GET['f'];
    array_push($_SESSION['productIds'],$newFairy);

        } else {$oldFairy = $_GET['f'];}
    }


    foreach($_SESSION['productIds'] as $newItem){
    $query = "SELECT * FROM products WHERE id = ?";
    if($getFairy = $sqlConnection->prepare($query)){
        $getFairy->bind_param("i",$newItem);
        $getFairy->execute();
        $result = $getFairy->get_result();
        $row    = $result->fetch_array();
        $getFairy->close();

            $newProduct = new AddProduct($row);
            }

    if (!in_array($newProduct,$_SESSION['cartProducts'])){

        array_push($_SESSION['cartProducts'],$newProduct);
        $quantity   = new quantityUpdate($newProduct);
        array_push($_SESSION['quantity'],$quantity);
            print_r($_SESSION['quantity']);
                } else {

                        if(isset($oldFairy) != ""){
                        $founded = false;
                    foreach($_SESSION['quantity'] as $q){

                    if($q->id == $oldFairy && $founded != true){        
                        $q->update();
                        $founded = true;

                    print_r($_SESSION['quantity']);
                    echo "<br>count: ".count($_SESSION['quantity'])."<br>";

                            }
                        }
                    }
                }
            }


if($_SESSION['productIds'] != ""){

    $c = count($_SESSION['cartProducts']);


        if($c == 0){
        $outPutProduct = "<h3>כרגע אין מוצרים בעגלת הקניות</h3>";

        echo "<br>cartProducts: ".$c;
        echo "<br>productIds: ".count($_SESSION['productIds']);
        } else if ($c == 1){
        $outPutProduct = $_SESSION['cartProducts'][0]->output;

        echo "<br>cartProducts: ".$c;
        echo "<br>productIds: ".count($_SESSION['productIds']);
        } else {                

                $outPutProduct = $_SESSION['cartProducts'][0]->output;
            for($x=1; $x<count($_SESSION['cartProducts']);$x++){
                $outPutProduct .= "<hr>".$_SESSION['cartProducts'][$x]->output;

                }
                echo "<br>cartProducts: ".$c;
                echo "<br>productIds: ".count($_SESSION['productIds']);
        }

    } 

Class quantityUpdate{

    var $id;
    var $quantity = 1;

    function __construct($obj){
        $this->id = $obj->id;
        }

    function update(){
        $this->quantity += 1;
        }
    }   

Class AddProduct{

    var $image;
    var $name;
    var $selectQnty;
    var $desc;
    var $id;
    var $price;
    var $output;

    function __construct($fairy){
        $this->image        = $fairy['img'];
        $this->name         = $fairy['name'];
        $this->desc         = $fairy['description'];
        $this->id           = $fairy['id'];
        $this->price        = $fairy['price'];
        $this->selectQnty   = "<select id='quantity".$this->id."'>" 
                            ."<option id='1' value='1'>1</option>"
                            ."<option id='2' value='2'>2</option>"
                            ."<option id='3' value='3'>3</option>"
                            ."<option id='4' value='4'>4</option>"
                            ."<option id='5' value='5'>5</option>"
                            ."<option id='6' value='6'>6</option>"
                            ."<option id='7' value='7'>7</option>"
                            ."<option id='8' value='8'>8</option>"
                            ."<option id='9' value='9'>9</option>"
                            ."<option id='10' value='10'>10</option>"
                            ."</select>"
                            ."<span class='qnty'>x</span>";

        $this->output       = $this->image.$this->selectQnty
                            ."<span id='name' class='name'>".$this->name."</span>"
                            ."<span id='desc' class='desc'>".$this->desc."</span>"
                            ."<span id='id' class='id'>מק״ט: 000".$this->id."</span>"
                            ."<span id='price' class='price'>".$this->price."₪</span>"
                            ."<button onclick='removeItem(".$this->id.")' class='glyphicon glyphicon-remove'></button>";

        }   
    }

?>

try to put a break, and only do once whn firs concurrence:

$founded = false;
    foreach($_SESSION['quantity'] as $q){
    if($q->id == $sameProduct && !$founded){     
    $q->update();
$founded=true;
    return $founded;
        }
    }

Putting a semaphore, could be done, and try to look with a return stops the foreach

is it for you possible to use the id of your product as array key?

Like :

$_SESSION['quantity'][$sameProduct]

In this case you dont need to loop $_SESSION['quantity']

"break 2;" did it! the code:

    if(isset($existingProduct) != ""){
                foreach($_SESSION['quantity'] as $q){
                    if($existingProduct == $q->id){     
                    $q->update();
                    print_r($_SESSION['quantity']);
                    break 2;
                        }
                    }
                }

post answer #103:

" As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.

For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.

Source: Can you 'exit' a loop in PHP?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM