滤波器阵列 - 奇数偶数

时间:2009-04-10 16:31:43

标签: php arrays

如何过滤掉具有奇数或偶数索引号的数组条目?

Array
(
    [0] => string1
    [1] => string2
    [2] => string3
    [3] => string4
)

喜欢,我希望它从数组中删除[0]和[2]条目。 或者说我有0,1,2,3,4,5,6,7,8,9 - 我需要删除0,2,4,6,8。

7 个答案:

答案 0 :(得分:15)

foreach($arr as $key => $value) if($key&1) unset($arr[$key]);

以上从阵列中删除奇数位置,删除偶数位置,使用以下内容:

而是if($key&1)您可以使用if(!($key&1))

答案 1 :(得分:2)

这是一个“hax”解决方案:

将array_filter与“isodd”函数结合使用。

array_filter似乎只处理值,所以你可以先使用array_flip然后使用array_filter。

array_flip(array_filter(array_flip($data), create_function('$a','return $a%2;')))

答案 2 :(得分:2)

你也可以像这样使用SPL FilterIterator:

class IndexFilter extends FilterIterator {
    public function __construct (array $data) {
        parent::__construct(new ArrayIterator($data));
    }   

    public function accept () {
        # return even keys only
        return !($this->key() % 2);
    }     
}

$arr      = array('string1', 'string2', 'string3', 'string4');
$filtered = array();

foreach (new IndexFilter($arr) as $key => $value) {
    $filtered[$key] = $value;
}

print_r($filtered);

答案 3 :(得分:1)

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

答案 4 :(得分:0)

我会这样做......

for($i = 0; $i < count($array); $i++)
{
    if($i % 2) // OR if(!($i % 2))
    {
        unset($array[$i]);
    }
}

答案 5 :(得分:0)

<?php 
$array = array(0, 3, 5, 7, 20, 10, 99,21, 14, 23, 46); 
for ($i = 0; $i < count($array); $i++) 

{ 
        if ($array[$i]%2 !=0)
        echo $array[$i]."<br>";
}
?> 

答案 6 :(得分:0)

/path/to/node_modules/foundation-sites/dist/js/foundation.d.ts

这个答案比this答案有点改进。您可以使用匿名函数代替$array = array(0 => 'string1', 1 => 'string2', 2 => 'string3', 3 => 'string4'); // Removes elements of even-numbered keys $test1 = array_filter($array, function($key) { return ($key & 1); }, ARRAY_FILTER_USE_KEY); // Removes elements of odd-numbered-keys $test2 = array_filter($array, function($key) { return !($key & 1); }, ARRAY_FILTER_USE_KEY); 。此外,create_function采用可选的标志参数,允许您指定回调函数将密钥作为其唯一参数。因此,您无需使用array_filter来获取密钥数组。

相关问题