当前位置:Gxlcms > PHP教程 > php拆分数组的二个函数(array_slice()、array_splice())

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

时间:2021-07-01 10:21:17 帮助过:4人阅读

  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. ?>

人气教程排行