array_slice和array_splice函數是用在取出數組的一段切片,array_splice還有用新的切片替換原刪除切片位置的功能。類似javascript中的Array.prototype.splice和Array.prototype.slice方法。
我在github上有對PHP源碼更詳細的注解。感興趣的可以圍觀一下,給個star。PHP5.4源碼注解??梢酝ㄟ^commit記錄查看已添加的注解。
array_slicearray array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
返回數組中指定下標offset和長度length的子數組切片。
參數說明設第一個參數數組的長度為num_in。
offset如果offset是正數且小于length,則返回數組會從offset開始;如果offset大于length,則不操作,直接返回。如果offset是負數,則offset = num_in+offset,如果num_in+offset == 0,則將offset設為0。
length如果length小于0,那么會將length轉為num_in - offset + length;否則,如果offset+length > array_count,則length = num_in- offset。如果處理后length還是小于0,則直接返回。
preserve_keys默認是false,默認不保留數字鍵值原順序,設為true的話會保留數組原來的數字鍵值順序。
使用實例<?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 'd'$output = array_slice($input, 0, 3); // returns 'a', 'b', and 'c'print_r(array_slice($input, 2, -1)); // array(0 => 'c', 1 => 'd');print_r(array_slice($input, 2, -1, true)); // array(2 => 'c', 1 => 'd');運行步驟
處理參數:offset、length
移動指針到offset指向的位置
從offset開始,拷貝length個元素到返回數組
運行流程圖如下
array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement = array() ]] )
刪除input中從offset開始length個元素,如果有replacement參數的話用replacement數組替換刪除掉的元素。
參數說明array_splice函數中的offset和length參數跟array_slice函數中的用法一樣。
replacement如果這個參數設置了,那么函數將使用replacement數組來替換。
如果offset和length指定了沒有任何元素需要移除,那么replacement會被插入到offset的位置。
如果replacement只有一個元素,可以不用array()去包著它。
使用示例<?php$input = array('red', 'green', 'blue', 'yellow');array_splice($input, 2);// $input變為 array('red', 'green')$input = array('red', 'green', 'blue', 'yellow');array_splice($input, 1, -1);// $input變為 array('red', 'yellow')$input = array('red', 'green', 'blue', 'yellow');array_splice($input, 1, count($input), 'orange');// $input變為 array('red', 'orange')$input = array('red', 'green', 'blue', 'yellow');array_splice($input, -1, 1, array('black', 'maroon'));// $input為 array('red', 'green',// 'blue', 'black', 'maroon')$input = array('red', 'green', 'blue', 'yellow');array_splice($input, 3, 0, 'purple');// $input為 array('red', 'green',// 'blue', 'purple', 'yellow');源碼解讀
在array_splice中,有這么一段代碼:
/* Don't create the array of removed elements if it's not going * to be used; e.g. only removing and/or replacing elements */ if (return_html' target='_blank'>value_used) { // 如果有用到函數返回值則創建返回數組,否則不創建返回數組 int size = length; /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { size = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { size = num_in - offset; } /* Initialize return value */ array_init_size(return_value, size > 0 ? size : 0); rem_hash = &Z_ARRVAL_P(return_value); }鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答