array_filter 数组过滤器

PHP数组过滤
本文介绍了PHP中使用array_filter函数的不同方式,包括回调函数的应用、删除特定值及类中的使用方法。
1: 有回调函数

<?php
function odd($var)
{
    return($var % 2 == 1);
}

function even($var)
{
    return($var % 2 == 0);
}

$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"));
?> 

output:

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



2: 无回调函数

<?php

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?> 

output:

Array
(
    [0] => foo
    [2] => -1
)

3: 第二个参数直接写回调函数(实现)

Here is how you could easily delete a specific value from an array with array_filter: 

<?php 
$array = array (1, 3, 3, 5, 6); 
$my_value = 3; 
$filtered_array = array_filter($array, function ($element) use ($my_value) { return ($element != $my_value); } ); 
print_r($filtered_array); 
?> 

output: 

Array 
( 
    [0] => 1 
    [3] => 5 
    [4] => 6 
)

4: (OOP)类中的应用

Don't forget that using callbacks in a class requires that you reference the object name in the callback like so:

<?php

$newArray = array_filter($array, array($this,"callback_function")); 

?>

Where "$this" is the reference to your object.

转载于:https://my.oschina.net/liuhui1990/blog/33074

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值