什么是PHP删除数组项的最佳方式? [英] What is the best way to delete array item in PHP?
本文介绍了什么是PHP删除数组项的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你能告诉我你的方式来从数组中删除一个项目?你觉得这是很好的?
Could you tell me your way to delete an item from array? Do you think it's good?
推荐答案
这取决于:
$a1 = array('a' => 1, 'b' => 2, 'c' => 3);
unset($a1['b']);
// array('a' => 1, 'c' => 3)
$a2 = array(1, 2, 3);
unset($a2[1]);
// array(0 => 1, 2 => 3)
// note the missing index 1
// solution 1 for numeric arrays
$a3 = array(1, 2, 3);
array_splice($a3, 1, 1);
// array(0 => 1, 1 => 3)
// index is now continous
// solution 2 for numeric arrays
$a4 = array(1, 2, 3);
unset($a4[1]);
$a4 = array_values($a4);
// array(0 => 1, 1 => 3)
// index is now continous
未设置()
是哈希表(字符串索引的数组)的安全,但如果你要依靠连续的数字指标,你将不得不使用任何的 array_splice()
或取消设置()
和 array_values()
。
这篇关于什么是PHP删除数组项的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文