从数组中删除

时间:2013-05-26 15:24:46

标签: php arrays

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

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],即:{/ p>

[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]);
    }
}

我该如何实现?感谢

2 个答案:

答案 0 :(得分: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)

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

答案 1 :(得分: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'
    ) 
);

希望它有所帮助。