Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从数组PHP中删除元素_Php_Arrays - Fatal编程技术网

从数组PHP中删除元素

从数组PHP中删除元素,php,arrays,Php,Arrays,我有一个数组,中间部分根据产品的数量变化 Array ( [name] => Alberto [email] => email@hotmail.com [code_1] => tshirt [description_1] => Tshirt color red [price_1] => 453.0 [quantity_1] => 1 [subtotal_1] => 453.0 [code_2] => sweater [description_2]

我有一个数组,中间部分根据产品的数量变化

Array ( [name] => Alberto [email] => email@hotmail.com [code_1] => tshirt [description_1] => Tshirt color red [price_1] => 453.0 [quantity_1] => 1 [subtotal_1] => 453.0 [code_2] => sweater [description_2] => Sweater with long sleeves [price_2] => 23.43 [quantity_2] => 2 [subtotal_2] => 46.86 [employee] => 1 [total] => 499.86 )
我想删除前两个元素,最后两个元素,离开

Array ( [code_1] => tshirt [description_1] => Tshirt color red [price_1] => 453.0 [quantity_1] => 1 [subtotal_1] => 453.0 [code_2] => sweater [description_2] => Sweater with long sleeves [price_2] => 23.43 [quantity_2] => 2 [subtotal_2] => 46.86 )
我试着用

array_splice($_POST, 2, -2);
但这只保留前2个和后2个,我需要它们之间的元素


感谢您的帮助:)

使用
array\u Slice()
从第三项(偏移量2)到最后减去最后2项进行切片:

$result = array_slice($_POST, 2, -2);
array_splice($_POST, 0, 2);
array_splice($_POST, -2);
注意:如果你的数组明显小于等于4项,你将什么也得不到

要使用
阵列拼接()
,请先卸下前两个,然后卸下最后两个:

$result = array_slice($_POST, 2, -2);
array_splice($_POST, 0, 2);
array_splice($_POST, -2);
由于这是一个关联数组,因此无论顺序如何,最好只获取所需的关键点:

$wanted = array('price_1', 'quantity_1'); // etc...
$result = array_intersect_key($_POST, array_flip($wanted));

由于数据结构是散列映射,因此不应删除带有数字索引(键位置)的元素。

它是一个散列映射,不能在索引(键位置)上中继,只能在键上中继

使用
unset
指令从数组(哈希映射)中删除任何元素

unset($arr['name'], $arr('email'));

当你说删除时,你需要数据还是不需要?您可以简单地
unset($array['name'])
和其他,如果您不需要它们
$result=array\u slice($\u POST,2,count($\u POST)-4)也许吧。实际上这很有效,非常感谢Abracadver:)您可以为array_slice的length参数提供
-2
,从末尾开始倒数,而不是length-4。因为我知道排序产品的部分,所以此方法也有效:unset($_POST['name');取消设置($_POST['email']);未设置($_POST['employee']);未设置($_POST['total']);添加了另一个选项,因为您应该知道需要什么键。如果您对键使用任意数值,则array_slice函数可能会让您感到惊讶,也就是说,使用像array_slice这样的容易出错的函数没有任何借口和好处。有
array_slice
array_splice
函数允许通过数字索引从数组中移除元素,而不考虑键。我添加了一种可能更好的方法,因为我希望OP知道他们需要哪些键。