PHP 如何截断一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7985416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:43:18 来源:igfitidea点击:
PHP how to truncate an array
提问by Alexander Farber
How do you truncate a PHP array in a most effective way?
如何以最有效的方式截断 PHP 数组?
Should I use array_splice?
我应该使用array_splice吗?
采纳答案by Peter
You can use the native functions to remove array elements:
您可以使用本机函数删除数组元素:
- array_pop- Pop the element off the end of array
- array_shift- Shift an element off the beginning of array
- array_slice- Extract a slice of the array
- unset- Remove one element from array
- array_pop- 从数组末尾弹出元素
- array_shift- 将一个元素从数组的开头移开
- array_slice- 提取数组的一个切片
- unset- 从数组中删除一个元素
With this knowledge make your own function
有了这些知识,让你自己的功能
function array_truncate(array $array, $left, $right) {
$array = array_slice($array, $left, count($array) - $left);
$array = array_slice($array, 0, count($array) - $right);
return $array;
}
回答by Marc B
回答by uglypointer
This function should work
这个功能应该可以工作
function truncateArray($truncateAt, $arr) {
array_splice($arr, $truncateAt, (count($arr) - $truncateAt));
return $arr;
}
回答by Devtronic
You can use one of this functions:
您可以使用以下功能之一:
function array_truncate(&$arr)
{
while(count($arr) > 0) array_pop($arr);
}
// OR (faster)
function array_truncate2(&$arr)
{
array_splice($arr, 0, count($arr));
}
Usage:
用法:
$data2 = array("John" => "Doe", "Alice" => "Bob");
array_truncate($data2);
// OR
array_truncate2($data2);