我不明白为什么这段代码不仅会删除带有通过URL传递的给定密钥的pizza_id。我回显$_GET['key']
值来检查我是否有所需的数字,它运行正常。
关键值来自构建购物车的另一个foreach $key=>$value
循环,并且具有带有披萨ID和其中的$ key的删除链接。
switch ($action) {
case 'add':
if ($cart) {
$cart .= ','.$_GET['pizza_id'];
} else {
$cart = $_GET['pizza_id'];
}
break;
case 'delete':
echo "KEY: ".$_GET['key']."<br>";
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $key => $item)
{
if ($_GET['pizza_id'] != $item && $GET['key']!= $key )
{
if ($newcart != '')
{
$newcart .= ','.$item;
}
else
{
$newcart = $item;
}
}
}
$cart = $newcart;
}
break;
}
编辑:也许我还应该提一下代码的基础来自这个网页http://v3.thewatchmakerproject.com/journal/276/
答案 0 :(得分:0)
检查这是否有效
foreach ($items as $key => $item)
{
if ($_GET['pizza_id'] != $item && $GET['key']!= $item )
答案 1 :(得分:0)
我没有解决你的问题...但你在if条件下有一个错字。
$GET[
没有下划线......
答案 2 :(得分:0)
嗯,至少,你不需要foreach中的$ key。
if ($cart) {
// you car is now an array of $items.
$items = explode(',',$cart);
$key = $_GET[ 'key' ];
// are you sure pizza_id is correct too? You may want to echo/log it
// if there is an $item which corresponds to $key, remove it.
if( isset( $items[ $key ] ) )
unset( $items[ $key ] );
// this loop searches for all indexes of $_GET[ 'pizza_id' ] and removes them
// comment this out if you don't want to do that. For some reason
// I missed it the first go round.
while( ($pos = $array_search( $items, $_GET[ 'pizza_id' ] ) !== FALSE )
{
array_splice( $items, $pos, 1 );
}
// implode afterwards
$cart = implode( ',', $items );
}
另一张海报指出您的原始代码也有$GET['key']
。坏处10000.您是否在开发过程中将警告和错误输出设置为最高级别?