欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php拆分数组的二个函数(array_slice()、array_splice())

程序员文章站 2022-03-15 22:41:48
...
  1. $input = array("a", "b", "c", "d", "e");

  2. $output = array_slice($input, 2); // returns "c", "d", and "e"

  3. $output = array_slice($input, -2, 1); // returns "d"
  4. $output = array_slice($input, 0, 3); // returns "a", "b", and "c"
  5. // note the differences in the array keys

  6. print_r(array_slice($input, 2, -1));
  7. print_r(array_slice($input, 2, -1, true));
  8. ?>
复制代码

上例将输出: Array ( [0] => c [1] => d ) Array ( [2] => c [3] => d )

2.array_splice()

携带三个参数,同上,作用是删除从offset开始长度为length的子数组。

例子:

  1. $input = array("red", "green", "blue", "yellow");

  2. array_splice($input, 2);
  3. // $input is now array("red", "green")
  4. $input = array("red", "green", "blue", "yellow");

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

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

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

  15. array_splice($input, 3, 0, "purple");
  16. // $input is now array("red", "green",
  17. // "blue", "purple", "yellow");
  18. ?>
复制代码