php array_slice() 函數

來源:互聯網
上載者:User

PHP array_slice() 函數
PHP Array 函數
定義和用法
array_slice() 函數在數組中根據條件取出一段值,並返回。

注釋:如果數組有字串鍵,所返回的數組將保留鍵名。(參見例子 4)

文法
array_slice(array,offset,length,preserve)參數 描述
array 必需。規定輸入的數組。
offset 必需。數值。規定取出元素的開始位置。

如果是正數,則從前往後開始取,如果是負值,從後向前取 offset 絕對值。
 
length 可選。數值。規定被返回數組的長度。

如果是負數,則從後向前,選取該值絕對值數目的元素。如果未設定該值,則返回所

有元素。
 
preserve 可選。可能的值:

true - 保留鍵
false - 預設 - 重設鍵
 


<?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 "c", "d"
$output = array_slice ($input, -2, 1); // returns "d"
$output = array_slice ($input, 0, 3); // returns "a", "b", and "c"
?>


執行個體

<?php
$term = $_REQUEST['q'];
$images = array_slice(scandir("images"), 2);
foreach($images as $value) {
 if( strpos(strtolower($value), $term) === 0 ) {
  echo $value . " ";
 }
}
?>

<?php
// split the given array into n number of pieces
function array_split($array, $pieces=2)
{  
    if ($pieces < 2)
        return array($array);
    $newCount = ceil(count($array)/$pieces);
    $a = array_slice($array, 0, $newCount);
    $b = array_split(array_slice($array, $newCount), $pieces-1);
    return array_merge(array($a),$b);
}

// Examples:
$a = array(1,2,3,4,5,6,7,8,9,10);
array_split($a, 2);    // array(array(1,2,3,4,5), array(6,7,8,9,10))
array_split($a, 3);    // array(array(1,2,3,4), array(5,6,7), array

(8,9,10))
array_split($a, 4);    // array(array(1,2,3), array(4,5,6), array(7,8),

array(9,10))

?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.