PHP 数组函数,从数组中去除一段序列

PHP 数组函数,这两个以前 没用到,现在看起来挺有用
array_slice — 从数组中取出一段
array_splice — 把数组中的一部分去掉并用其它值取代

array_slice

(PHP 4, PHP 5, PHP 7)
array_slice — 从数组中取出一段

说明 

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
array_slice() 返回根据 offset 和 length 参数所指定的 array 数组中的一段序列。

参数 

array
输入的数组。

offset
如果 offset 非负,则序列将从 array 中的此偏移量开始。如果 offset 为负,则序列将从 array 中距离末端这么远的地方开始。

length
如果给出了 length 并且为正,则序列中将具有这么多的单元。如果给出了 length 并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从 offset 开始一直到 array 的末端。

preserve_keys
注意 array_slice() 默认会重新排序并重置数组的数字索引。你可以通过将 preserve_keys 设为 TRUE 来改变此行为。

用例1
<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
以上例程会输出:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

array_splice

(PHP 4, PHP 5, PHP 7)
array_splice — 把数组中的一部分去掉并用其它值取代

说明 

array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] )
把 input 数组中由 offset 和 length 指定的单元去掉,如果提供了 replacement 参数,则用其中的单元取代。

注意 input 中的数字键名不被保留。

Note: If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement.
参数 

input
输入的数组。

offset
如果 offset 为正,则从 input 数组中该值指定的偏移量开始移除。如果 offset 为负,则从 input 末尾倒数该值指定的偏移量开始移除。

length
如果省略 length,则移除数组中从 offset 到结尾的所有部分。如果指定了 length 并且为正值,则移除这么多单元。如果指定了 length 并且为负值,则移除从 offset 到数组末尾倒数 length 为止中间所有的单元。小窍门:当给出了 replacement 时要移除从 offset 到数组末尾所有单元时,用 count($input) 作为 length。

replacement
如果给出了 replacement 数组,则被移除的单元被此数组中的单元替代。

如果 offset 和 length 的组合结果是不会移除任何值,则 replacement 数组中的单元将被插入到 offset 指定的位置。 注意替换数组中的键名不保留。

如果用来替换 replacement 只有一个单元,那么不需要给它加上 array(),除非该单元本身就是一个数组、一个对象或者 NULL。

返回值 

返回一个包含有被移除单元的数组。

用例1
<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

收起正文

原文地址:https://www.cnblogs.com/haoyuekey/p/12793975.html