php array_slice 函數(shù)在數(shù)組中根據(jù)條件取出一段值,并返回。如果數(shù)組有字符串鍵,所返回的數(shù)組將保留鍵名。本文章通過實例向大家講解array_slice 函數(shù)的使用方法。
php array_slice — 從數(shù)組中取出一段
array_slice 函數(shù)基本語法:
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
array_slice() 返回根據(jù) offset 和 length 參數(shù)所指定的 array 數(shù)組中的一段序列。
參數(shù)介紹
參數(shù) | 描述 |
---|---|
array | 必需。輸入的數(shù)組。 |
soffset |
必需。數(shù)值。規(guī)定取出元素的開始位置。 0 = 第一個元素。 如果 offset 非負(fù),則序列將從 array 中的此偏移量開始。如果 offset 為負(fù),則序列將從 array 中距離末端這么遠(yuǎn)的地方開始。 |
length |
可選。數(shù)值。規(guī)定被返回數(shù)組的長度。 如果給出了 length 并且為正,則序列中將具有這么多的單元。如果給出了 length 并且為負(fù),則序列將終止在距離數(shù)組末端這么遠(yuǎn)的地方。如果省略,則序列將從 offset 開始一直到 array 的末端。 |
preserve_keys |
可選。規(guī)定函數(shù)是保留鍵名還是重置鍵名。可能的值:
默認(rèn)會重新排序并重置數(shù)組的數(shù)字索引。你可以通過將 preserve_keys 設(shè)為 TRUE 來改變此行為。 |
返回值
返回其中一段。
實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php $input = array ( "a" , "b" , "c" , "d" , "e" ); $output = array_slice ( $input , 2); print_r( $output ); echo "<br/><br/>" ; $output = array_slice ( $input , -2, 1); print_r( $output ); echo "<br/><br/>" ; $output = array_slice ( $input , 0, 3); print_r( $output ); echo "<br/><br/>" ; print_r( array_slice ( $input , 2, -1)); echo "<br/><br/>" ; print_r( array_slice ( $input , 2, -1, true)); ?> |
結(jié)果:
1
2
3
4
5
6
7
|
"; $output = array_slice($input, -2, 1); print_r($output);echo " "; $output = array_slice($input, 0, 3); print_r($output);echo " "; print_r(array_slice($input, 2, -1));echo " "; print_r( array_slice ( $input , 2, -1, true)); ?> |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!