说这是你的$_SESSION['basket']:
Array
(
[0] => Array
(
[id] => 12
[name] => some name
[color] => some color
)
[1] => Array
(
[id] => 8
[name] => some name
[color] => some color
)
[2] => Array
(
[id] => 3
[name] => some name
[color] => some color
)
[3] => Array
(
[id] => 22
[name] => some name
[color] => some color
)
)
首先你需要遍历数组$_SESSION['basket']的所有单个元素:
foreach ($_SESSION['basket'] as $i => $product) {
/*
$i will equal 0, 1, 2, etc.
and is the position of the product within the basket array.
$product is an array of itself, which will equal e.g.:
Array
(
[id] => 12
[name] => some name
[color] => some color
)
*/
}
现在您想知道产品的 id 是否与您要查找的产品的 ID 匹配。您不需要遍历$product 数组的每个元素来执行此操作,假设您的 ID 将始终命名为“id”。只需检查 id 字段即可:
foreach ($_SESSION['basket'] as $i => $product) {
if ($product['id'] == $someId) {
// at this point you want to remove this whole product from the basket
// you know that this is element no. $i, so unset it:
unset($_SESSION['basket'][$i]);
// and stop looping through the rest,
// assuming there's only 1 product with this id:
break;
}
}
请注意,检查值而不是键也存在危险。假设您有一个这样构建的产品:
Array
(
[count] => 12
[id] => 5
[name] => some name
[color] => some color
)
如果您检查所有值,就像您现在所做的那样,并尝试将其与某个 id 匹配,那么当该 id 恰好是“12”时会发生什么?
// the id you're looking for:
$someId = 12;
foreach ($product as $key => $value) {
// first $key = count
// first $value = 12
if ($value == $someId) {
// ...
// but in this case the 12-value isn't the id at all
}
}
所以:始终引用数组中的特定元素,在本例中为“id”(或您在应用中使用的任何名称)。不要检查随机值,因为你不能绝对确定它匹配时,这实际上是你正在寻找的正确值。
祝你好运!