【发布时间】:2021-02-09 23:31:07
【问题描述】:
我正在尝试使用会话和循环编辑数组的数据。
此代码中的预期输出是,在循环内编辑特定数据,但问题是正在编辑其他数据。请帮我解决这个问题,谢谢。
注意:如果$cart_action 为add,则会添加新数据,但如果$values['type'] 等于$_POST['type'],则会编辑产品的具体数量。
例如,我想编辑product_id MQFUQ的数量,但我不知道如何编辑这个,product_id SHAREZ总是被编辑。 //数据 大批 ( [0] => 数组 ( [产品编号] => NP1DC [product_id] => 28AHT [类型] => SOLOZ [数量] => 1 )
[1] => Array
(
[product_number] => DZRW8
[product_id] => 28AHT
[type] => SHAREZ
[qty] => 1
)
[2] => Array
(
[product_number] => 4G0RY
[product_id] => MQFUQ
[type] =>
[qty] => 2
)
[3] => Array
(
[product_number] => ZS1C6
[product_id] => 28AHT
[type] => SOLOZ
[qty] => 1
)
)
//here's my code
$result = 0;
$values_type = "";
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
$values_type = $values['type'];
if($values["product_id"] == $_POST["product_id"] && $values['type'] == $_POST['type'])
{
$item_array = array(
'product_number' => $values['product_number'],
'product_id' => $_POST["product_id"],
'type' => $_POST["type"],
'qty' => $_POST['qty'] + $values['qty']
);
$_SESSION["shopping_cart"][$keys] = $item_array;
$result = $keys;
$cart_action = "edit";
}
else {
$values_type = $values['type'];
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'product_number' => $product_number,
'product_id' => $_POST["product_id"],
'type' => $_POST["type"],
'qty' => $_POST['qty']
);
$result = $count;
$cart_action = "add";
}
}
if ($cart_action == "add") {
$_SESSION["shopping_cart"][$result] = $item_array;
echo $cart_action ." ". $values_type;
}
elseif ($cart_action == "edit") {
$_SESSION["shopping_cart"][$result] = $item_array;
echo $cart_action ." ". $values_type;
}
else {
echo "";
}
【问题讨论】:
-
如果您显示原始数组(代表性样本
var_export())和目标数组会有所帮助。 -
@jibsteroos 您好,我已经编辑了我的帖子,请检查您是否有时间,谢谢先生。
-
首先 - 如果在这里中继您的代码,产品将始终被添加,而不是计算在内。您根据会话检查两件事 - 类型和 product_id。但是鉴于 var_dump 说类型总是不同的。其次 - 为什么让它这么难?检查会话项目的产品ID,如果有,会话项目数量+1,否则添加新产品