本文實(shí)例講述了PHP實(shí)現(xiàn)數(shù)組向任意位置插入,刪除,替換數(shù)據(jù)操作。分享給大家供大家參考,具體如下:
array_splice函數(shù)可以實(shí)現(xiàn)任意位置插入和刪除,替換
array array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] )
offset | 如果 offset 為正,則從 input 數(shù)組中該值指定的偏移量開始移除。如果 offset 為負(fù),則從 input 末尾倒數(shù)該值指定的偏移量開始移除。 |
length | 如果省略 length,則移除數(shù)組中從 offset 到結(jié)尾的所有部分。如果指定了 length 并且為正值,則移除這么多單元。如果指定了 length 并且為負(fù)值,則移除從 offset 到數(shù)組末尾倒數(shù) length 為止中間所有的單元。 如果設(shè)置了 length 為零,不會移除單元。 小竅門:當(dāng)給出了 replacement 時要移除從 offset 到數(shù)組末尾所有單元時,用 count($input) 作為 length。 |
replacement | 如果給出了 replacement 數(shù)組,則被移除的單元被此數(shù)組中的單元替代。 |
如果 offset 和 length 的組合結(jié)果是不會移除任何值,則 replacement 數(shù)組中的單元將被插入到 offset 指定的位置。 注意替換數(shù)組中的鍵名不保留。
如果用來替換 replacement 只有一個單元,那么不需要給它加上 array(),除非該單元本身就是一個數(shù)組、一個對象或者 NULL。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php $ input = array( "red" , "green" , "blue" , "yellow" ); $x = "black" ; $y = "purple" ; / / 添加兩個新元素到 $ input array_push($ input , $x, $y); array_splice($ input , count($ input ), 0 , array($x, $y)); / / 移除 $ input 中的最后一個元素 array_pop($ input ); array_splice($ input , - 1 ); / / 移除 $ input 中第一個元素 array_shift($ input ); array_splice($ input , 0 , 1 ); / / 在 $ input 的開頭插入一個元素 array_unshift($ input , $x, $y); array_splice($ input , 0 , 0 , array($x, $y)); / / 在 $ input 的索引 $x 處替換值 $ input [$x] = $y; / / 對于鍵名和偏移量等值的數(shù)組 array_splice($ input , $x, 1 , $y); |
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/z15818264727/article/details/81252513