0

我有一个看起来像这样的数组:

Array ( 
    [0] => Array ( 
        [id] => 18 
        [name] => book 
        [description] => 
        [quantity] => 0 
        [price] => 50 
        [status] => Brand New
    ) 
    [1] => Array ( 
        [id] => 19 
        [name] => testing   
        [description] => for testing 
        [quantity] => 2 
        [price] => 182 
        [status] => Brand New
    ) 
    [2] => Array ( 
        [id] => 1 
        [name] => Fruity Loops 
        [description] => dj mixer 
        [quantity] => 1     
        [price]  => 200 
        [status] => Brand New
    ) 
)

我希望能够删除数组中的一整行(当用户单击删除链接时)说array[1]

[1] => Array ( 
    [id] => 19 
    [name] => testing   
    [description] => for testing 
    [quantity] => 2 
    [price] => 182 
    [status] => Brand New
)

我有这段代码,我试图根据产品的 id 删除,但它不起作用

//$_SESSION['items'] is the array and $delid is the "product id" gotten when a user clicks  delete on a particular row.
foreach ($_SESSION['Items'] as $key => $products) { 
    if ($products['id'] == $delid) {
        unset($_SESSION['Items'][$key]);
    }
}

我该如何实施?谢谢

4

2 回答 2

2

您可以将 $_session 传递给ArrayIterator并使用 ArrayIterator::offsetUnset()。

例如:-

session_start();

$_SESSION['test1'] = 'Test1';
$_SESSION['test2'] = 'Test2';
$_SESSION['test3'] = 'Test3';

var_dump($_SESSION);
$iterator = new ArrayIterator($_SESSION);
$iterator->offsetUnset('test2');
$_SESSION =  $iterator->getArrayCopy();

var_dump($_SESSION);

输出:-

array (size=3)
  'test1' => string 'Test1' (length=5)
  'test2' => string 'Test2' (length=5)
  'test3' => string 'Test3' (length=5)

array (size=2)
  'test1' => string 'Test1' (length=5)
  'test3' => string 'Test3' (length=5)

这也为您节省了遍历数组以查找要删除的元素的费用。

于 2013-05-26T15:28:43.253 回答
1

您进行删除的方式似乎没有问题。但我认为问题出在数组的结构上。例如,字符串值不被引用,数组项没有逗号分隔,数组键写在 [] 内。

尝试如下更改您的数组,删除应该可以正常工作:

$_SESSION['Items'] = Array ( 
    0 => Array ( 
        'id' => 18, 
        'name' => 'book',
        'description' => '',
        'quantity' => 0,
        'price' => 50,
        'status' => 'Brand New'
    ),
    1 => Array ( 
        'id' => 19,
        'name' => 'testing',
        'description' => 'for testing',
        'quantity' => 2,
        'price' => 182,
        'status' => 'Brand New',
    ),
    2 => Array ( 
        'id' => 1,
        'name' => 'Fruity Loops',
        'description' => 'dj mixer',
        'quantity' => 1,
        'price'  => 200,
        'status' => 'Brand New'
    ) 
);

希望能帮助到你。

于 2013-05-26T15:38:35.060 回答