尝试使用数组推送并使数组键等于产品ID,以便以后可以删除它。我尝试过没有工作的array_fill_keys。
PHP代码是:
$key = $_POST['product'];
for($i = 0; $i < count($_SESSION['cart_items']); $i++) {
$key_s = array_search($key, $_SESSION['cart_items'][$i]);
echo $key_s;
if ($_SESSION['cart_items'][$i][$key_s] == $key)
{
unset($_SESSION['cart_items'][$i]);
echo "found it";
}
else
{
echo "not found";
}
}
var_dump($_SESSION['cart_items']);
输出是:
not foundnot foundarray(2) {
[3]=>
array(3) {
["item_id"] => string(4) "1131"
["item_name"] => string(36) "10 Ways A Condom Can’t Protect You"
["item_qty"] => string(2) "12"
}
[4]=>
array(3) {
["item_id"] => string(4) "1131"
["item_name"] => string(36) "10 Ways A Condom Can’t Protect You"
["item_qty"] => string(2) "12"
}
}
0
答案 0 :(得分:0)
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$search = 'red';
foreach($array as $key => $item){
if($item == $search){
unset ($array[$key]);
}
}
print_r($array);
答案 1 :(得分:0)
我不确定,但是你过度复杂了吗?
$key = $_POST['product'];
for($i=0;$i<count($_SESSION['cart_items']);$i++){
if ($_SESSION['cart_items'][$i]['item_id'] == $key) {
unset($_SESSION['cart_items'][$i]);
echo "found it";
}
else {
echo "not found";
}
}
var_dump($_SESSION['cart_items']);
只需忽略$key_s
和array_search
即可。 $_POST['product']
应该包含item_id
,对吗?
修改强>
如果数组键不符合规定,则上述功能无法正常工作。你可以改用foreach
。
像:
foreach ($_SESSION['cart_times'] as $cart_key => $id) {
if ($id == $key) {
unset($_SESSION['cart_items'][$cart_key]);
echo "found it";
}
else {
echo "not found";
}
}