我不明白为什么这段代码不仅会删除通过URL传递的给定键的pizza_id。我回显$_GET['key']
值来检查我是否有所需的数字,它工作得很好。键值来自另一个foreach $key=>$value
循环,该循环构建了购物车,并有一个带有pizza 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/
至少,您不需要在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年坏处。在开发期间,您是否将警告和错误输出设置为最大级别?
检查是否可以
foreach ($items as $key => $item)
{
if ($_GET['pizza_id'] != $item && $GET['key']!= $item )
我不明白你的问题…但是你的if条件有个错别字
$GET[
缺少下划线…