【发布时间】:2017-06-12 14:06:05
【问题描述】:
我有一个php 会话数组,例如
('10/01/2017, '13/02/2017', '21/21/2107')
现在如何在 O(1) 中从该数组中添加元素或删除元素
【问题讨论】:
-
你想删除哪个元素,或者你想添加什么?
-
您需要
unset()、array_shift()或array_pop(),具体取决于您想做什么。
我有一个php 会话数组,例如
('10/01/2017, '13/02/2017', '21/21/2107')
现在如何在 O(1) 中从该数组中添加元素或删除元素
【问题讨论】:
unset()、array_shift() 或array_pop(),具体取决于您想做什么。
最简单的方法是获取值,删除项目,然后重新设置会话变量。
$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]);?
使用 unset() 函数从数组中删除和元素:
<?php
//session array O
unset(O["array"][1]);
?>
【讨论】: