[英]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. $_SESSION['quantity']
是一个对象数组。
let's say I already added a product with id = 1
to the array. 假设我已经向数组添加了id = 1
的产品。
Next I add same product with id = 1
, so now $sameProduct = 1
and is set. 接下来,我添加id = 1
相同产品,因此现在设置了$sameProduct = 1
。
$q->update()
increments by the property 'quantity' of that object by 1. $q->update()
以该对象的属性“ quantity”增加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 可以放一个信号灯,然后试着找一个回车停止foreach
is it for you possible to use the id of your product as array key? 您能否将产品的ID用作阵列键?
Like : 喜欢 :
$_SESSION['quantity'][$sameProduct]
In this case you dont need to loop $_SESSION['quantity'] 在这种情况下,您不需要循环$ _SESSION ['quantity']
"break 2;" “休息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: 发布答案#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. “如其他文章所述,您可以使用break关键字。提示但未解释的一件事是,该关键字可以采用一个数值来告诉PHP可以中断多少个级别。
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. 例如,如果您有三个互相嵌套的foreach循环试图查找一条信息,则可以执行“ break 3”来摆脱所有三个嵌套循环。 This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures. 这将适用于“ for”,“ foreach”,“ while”,“ do-while”或“ switch”结构。
Source: Can you 'exit' a loop in PHP? 资料来源: 您可以在PHP中“退出”循环吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.