繁体   English   中英

php foreach与if循环遍历对象数组,执行if条件对数组中的成员进行计时,而不是一次

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

$_SESSION['quantity']是一个对象数组。

假设我已经向数组添加了id = 1的产品。

接下来,我添加id = 1相同产品,因此现在设置了$sameProduct = 1

$q->update()以该对象的属性“ quantity”增加1。

当数组中只有一项时,该代码运行良好;当一项以上时,问题就开始了。 该代码运行的时间是数组中的项目,而不是该特定对象的项目。

   <?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>";

        }   
    }

?>

尝试休息一下,并且只有在一次并发之后才做:

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

可以放一个信号灯,然后试着找一个回车停止foreach

您能否将产品的ID用作阵列键?

喜欢 :

$_SESSION['quantity'][$sameProduct]

在这种情况下,您不需要循环$ _SESSION ['quantity']

“休息2;” 做到了! 编码:

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

发布答案#103:

“如其他文章所述,您可以使用break关键字。提示但未解释的一件事是,该关键字可以采用一个数值来告诉PHP可以中断多少个级别。

例如,如果您有三个互相嵌套的foreach循环试图查找一条信息,则可以执行“ break 3”来摆脱所有三个嵌套循环。 这将适用于“ for”,“ foreach”,“ while”,“ do-while”或“ switch”结构。

资料来源: 您可以在PHP中“退出”循环吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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