>php教程 >php手册 >[PHP源码阅读]array_slice和array_splice函数,slicesplice

[PHP源码阅读]array_slice和array_splice函数,slicesplice

WBOY
WBOY원래의
2016-06-13 08:38:39863검색

[PHP源码阅读]array_slice和array_splice函数,slicesplice

array_slice和array_splice函数是用在取出数组的一段切片,array_splice还有用新的切片替换原删除切片位置的功能。类似javascript中的Array.prototype.splice和Array.prototype.slice方法。

我在github上有对PHP源码更详细的注解。感兴趣的可以围观一下,给个star。PHP5.4源码注解。可以通过commit记录查看已添加的注解。

array_slice

<p>array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )</p>

返回数组中指定下标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的话会保留数组原来的数字键值顺序。

使用实例

<?<span>php
</span><span>$input</span> = <span>array</span>("a", "b", "c", "d", "e"<span>);

</span><span>$output</span> = <span>array_slice</span>(<span>$input</span>, 2);      <span>//</span><span> returns "c", "d", and "e"</span>
<span>$output</span> = <span>array_slice</span>(<span>$input</span>, -2, 1);  <span>//</span><span> returns "d"</span>
<span>$output</span> = <span>array_slice</span>(<span>$input</span>, 0, 3);   <span>//</span><span> returns "a", "b", and "c"</span>

<span>print_r</span>(<span>array_slice</span>(<span>$input</span>, 2, -1)); <span>//</span><span> array(0 => 'c', 1 => 'd');</span>
<span>print_r</span>(<span>array_slice</span>(<span>$input</span>, 2, -1, <span>true</span>)); <span>//</span><span> array(2 => 'c', 1 => 'd');</span>

运行步骤

<p>处理参数:offset、length</p>
<p>移动指针到offset指向的位置</p>
<p>从offset开始,拷贝length个元素到返回数组</p>

 

运行流程图如下

 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中,有这么一段代码:

    <span>/*</span><span> Don't create the array of removed elements if it's not going
     * to be used; e.g. only removing and/or replacing elements </span><span>*/</span>
    <span>if</span> (return_value_used) { <span>//</span><span> 如果有用到函数返回值则创建返回数组,否则不创建返回数组</span>
        <span>int</span> size =<span> length;

        </span><span>/*</span><span> Clamp the offset.. </span><span>*/</span>
        <span>if</span> (offset ><span> num_in) {
            offset </span>=<span> num_in;
        } </span><span>else</span> <span>if</span> (offset < <span>0</span> && (offset = (num_in + offset)) < <span>0</span><span>) {
            offset </span>= <span>0</span><span>;
        }

        </span><span>/*</span><span> ..and the length </span><span>*/</span>
        <span>if</span> (length < <span>0</span><span>) {
            size </span>= num_in - offset +<span> length;
        } </span><span>else</span> <span>if</span> (((unsigned <span>long</span>) offset + (unsigned <span>long</span>) length) ><span> (unsigned) num_in)         {
            size </span>= num_in -<span> offset;
        }

        </span><span>/*</span><span> Initialize return value </span><span>*/</span><span>
        array_init_size(return_value, size </span>> <span>0</span> ? size : <span>0</span><span>);
        rem_hash </span>= &<span>Z_ARRVAL_P(return_value);
    }</span>

array_splice函数返回的是被删除的切片。这段代码的意思是,如果array_splice需要返回值,那么才创建返回数组,否则不创建,以免浪费空间。这也是一个编程小技巧,仅当需要的时候才返回。比如在函数中使用$result = array_splice(...),那么return_value_used就是true。

总结

到此本文结束,在平时编程中,应当像这两个函数实现时的做法一样,将最特殊的情况先处理掉,然后再继续,以免做了多余的判断;有需要保存新变量的时候才申请新的空间,不然会造成浪费。

 

原创文章,文笔有限,才疏学浅,文中若有不正之处,万望告知。

如果本文对你有帮助,请点下推荐吧,谢谢^_^

 

最后再安利一下,我在github有对PHP源码更详细的注解。感兴趣的可以围观一下,给个star。PHP5.4源码注解。可以通过commit记录查看已添加的注解。

更多源码文章,欢迎访问个人主页继续查看:hoohack

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.