【问题标题】:How to remove a single element from a PHP session array?如何从 PHP 会话数组中删除单个元素?
【发布时间】:2017-06-12 14:06:05
【问题描述】:

我有一个php 会话数组,例如

('10/01/2017, '13/02/2017', '21/21/2107')

现在如何在 O(1) 中从该数组中添加元素或删除元素

【问题讨论】:

  • 你想删除哪个元素,或者你想添加什么?
  • 您需要unset()array_shift()array_pop(),具体取决于您想做什么。

标签: php arrays session


【解决方案1】:

最简单的方法是获取值,删除项目,然后重新设置会话变量。

$data = $_SESSION['array'];    // Get the value
unset($data[1]);               // Remove an item (hardcoded the second here)
$_SESSION['array'] = $data;    // Set the session value with the new array

更新:
或者像@Qirel 说的,如果你知道数字,你可以直接取消设置项目。

unset($_SESSION['array'][1]);

更新 2
如果要按值删除元素,可以使用array_search 查找该元素的键。请注意,如果存在具有此值的元素,则只会删除第一个元素。

$value_to_delete = '13/02/2017';
if (($key = array_search($value_to_delete, $_SESSION['array'])) !== false)
    unset($_SESSION['array'][$key]);

【讨论】:

  • 为什么不只是unset($_SESSION['array'][1]);
  • 我的意思是,你的会工作并获得相同的结果 - 但它是额外的两行;-)
  • 我不知道索引值..我只是想删除 rhe 元素说 '13/02/2017'.. 我该怎么做..?
  • 非常感谢
【解决方案2】:

使用 unset() 函数从数组中删除和元素:

 <?php
  //session array O
  unset(O["array"][1]);
 ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2015-06-15
    • 1970-01-01
    • 2011-01-14
    • 2015-08-29
    • 1970-01-01
    相关资源
    最近更新 更多