删除 PHP 中的选择选项(带会话)


Delete options of a select in PHP (with sessions)

我对会话的取消设置有问题,因为我已经在函数上完成了它,并且只有内部参数删除了选择值 id。

看一看:

/***
 * @name DeleteItem
 * @date 04.10.2014
 * @param   The array that contains the element to delete
 * @param   The id of the selected index
 * @param   The name of the button that start the delete
 * @version 1.0
 * @description Delete an item to the select
 */
function DeleteItem($array,$SelectID,$btnDelete) {
    //The delete button was clicked?
    if(isset($_POST[$btnDelete]))
    {
    //Find the element with the id and delete the value
    foreach ($array as $idx =>$value)
    {
        if ($idx == $SelectID)
        {
             unset($array,$SelectID);
        }
    }
    return $array;
    } 

谢谢 - 我确信这是一件非常简单的事情。

您的unset()语法对于您尝试执行的操作类型是错误的。您只想从数组中删除索引$SelectID。尝试以下代码:

unset($array[$SelectID]);

此外,您不需要循环。以下是简化版本:

function DeleteItem($array,$SelectID,$btnDelete) {
   //The delete button was clicked? and if index exists in array
   if(isset($_POST[$btnDelete]) && array_key_exists($SelectID, $array)) {
         unset($array[$SelectID]);
   }
   return $array;
}

并且,仅当 POST 变量存在时,才需要删除(调用 DeleteItem() )。因此,您可以进一步简化如下,并从if条件中删除isset($_POST[$btnDelete])

if(isset($_POST[$btnDelete])) {
   DeleteItem($array,$SelectID);
}

您使用的"unset"不正确。

如果$SelectID是数组的值,

$index = array_search($SelectID, $array);
if ($index) {
  unset($array[$index]);
}

或者,如果$SelectID是数组的"键"而不是值,那么......

$keys = array_keys($array);
$index = array_search($SelectID, $keys);
if (!empty($keys[$index])) {
   unset($array[$keys[$index]]);
}
print_r($array);

(诗篇:我们不需要foreach)

最后发现只是一个参考值的问题(我正在处理副本)我只是添加一个 & 之前函数