PHP in_array 在会话循环后不工作
PHP in_array not working after loop in session
我有一个 foreach
循环来检查 ID
和 if
的所有数组,使用 in_array
查看 IDs
的任何数组是否是等于我的 $_POST['id']
如下所示:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
foreach ($_SESSION['cart'] as $item) {
$id = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}
出于某种原因,即使 ID
存在于 IDs
的数组列表中,它也会继续添加。
您只是在 foreach 循环中更改 $id 的值。尝试将值存储在数组中。参考以下代码:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
$id = array();
foreach ($_SESSION['cart'] as $item) {
$id[] = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}
我有一个 foreach
循环来检查 ID
和 if
的所有数组,使用 in_array
查看 IDs
的任何数组是否是等于我的 $_POST['id']
如下所示:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
foreach ($_SESSION['cart'] as $item) {
$id = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}
出于某种原因,即使 ID
存在于 IDs
的数组列表中,它也会继续添加。
您只是在 foreach 循环中更改 $id 的值。尝试将值存储在数组中。参考以下代码:
$cart = array (
'title' => $_POST['title'],
'price' => $_POST['price'],
'img_src' => $_POST['img_src'],
'id' => $_POST['id'],
);
$id = array();
foreach ($_SESSION['cart'] as $item) {
$id[] = $item['id'];
}
if(in_array($_POST['id'], $id)){
echo "ID exist";
}else{
$_SESSION['cart'][] = $cart;
$count = count($_SESSION["cart"]);
}