Deleting from an array
本问题已经有最佳答案,请猛点这里访问。
我有一个这样的数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 ) ) |
我希望能够删除数组中的整行(当用户单击删除链接时),比如
1 2 3 4 5 6 7 8 | [1] => Array ( [id] => 19 [name] => testing [description] => for testing [quantity] => 2 [price] => 182 [status] => Brand New ) |
我有一个代码,我试图根据产品的ID删除它,但它不起作用
1 2 3 4 5 6 | //$_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]); } } |
我如何实现这一点?谢谢
您可以将$_会话传递到arrayIterator,并使用arrayIterator::offsetunet()。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 | 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); |
输出:
1 2 3 4 5 6 7 8 |
这还节省了通过数组循环查找要删除的元素的开销。
删除的方式似乎没有问题。但我认为问题在于数组的结构。例如,字符串值不带引号,数组项之间没有逗号分隔,数组键写在[]内。
尝试按如下方式更改数组,删除操作将正常工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | $_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' ) ); |
希望它有帮助。