PHP数组切片改进版

时间:2014-02-12 11:38:31

标签: php arrays slice

我想知道是否有一个干净的方法来切割具有位置条件的数组,因此(例如)每个第五个元素将被删除,而Versa(例如)只选择第五个元素。

<?php
$input = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");

print_r ( array_slice ( $input, 0, count($input) ) ); //works but not what I need.

// This is not the correct syntax but just to get the idea

// print_r ( array_slice ( $input, 0, count($input) ) , {ONLY IF POSITION IS NOT MOD 5 SO 5,10,15,20,25 ... (ETC) WILL BE DROPPED} );

// AND VICE VERSA

// print_r ( array_slice ( $input, 0, count($input) ) , {ONLY IF POSITION IS MOD 5 SO IT WILL SELECT POSITION 5,10,15,20,25 ... (ETC) } );

?>

如果没有专门的php命令用于该任务循环就可以了:)

谢谢!

3 个答案:

答案 0 :(得分:0)

为什么不写自己的版本?

<?php
    $input = array(
        "a", "b", "c", "d", "e", "f", "g",
        "h", "i", "j", "k", "l", "m"
    );
    $removeElementAtInterval = 5;
    foreach($input as $key => $value) {
        if($key % $removeElementAtInterval == 0 && $key != 0) {
            unset($input[$key - 1]);
        }
    }
    print_r($input);
?>

<强> OUTPUT :

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [5] => f
    [6] => g
    [7] => h
    [8] => i
    [10] => k
    [11] => l
    [12] => m
)

答案 1 :(得分:0)

<?php
    function array_filter_with_index(array $arr, $callback = null)
    {   
        if (!is_callable($callback)) {
            return $arr;
        }

        $result = array();

        for ($i = 0; $i < count($arr); $i++) {
            if ($callback($i, $arr[$i])) {
                $result[] = $arr[$i];
            }
        }

        return $result;
    }

    function mod_by_5($idx, $elt)
    {   
        return ($idx % 5) === 0;
    }

    function not_mod_by_5($idx, $elt)
    {   
        return ($idx % 5) !== 0;
    }

    $input = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m");

    var_dump(array_filter_with_index($input, 'mod_by_5'));
    var_dump(array_filter_with_index($input, 'not_mod_by_5'));

    // Or with anonymous functions:
    $result = array_filter_with_index($input, function($idx, $elt) {
        return $idx > 6;
    });

    var_dump($result);
?>

答案 2 :(得分:0)

使用以下功能:

function array_remove_nth($array, $nth)
{
    for($i = 0; $i < count($array); $i+=$nth)
        unset($array[$i]);

    return $array;
}

function array_select_nth($array, $nth)
{
    $returnArr = array();
    for($i = 0; $i < count($array); $i+=$nth)
        $returnArr[] = $array[$i];

    return $returnArr;
}

打电话给他们:

$removedArr = array_remove_nth($yourArray, 5);
$selectedArr = array_select_nth($yourArray, 5);