编程语言
首页 > 编程语言> > PHP 中怎么实现根据某个值过滤数组?

PHP 中怎么实现根据某个值过滤数组?

作者:互联网

使用 array_filter 函数

array_filter 函数可以用来过滤数组中的元素,根据回调函数的返回值决定是否保留该元素。

示例 1:过滤数组中某个键的值

假设你有一个数组,每个元素都是一个关联数组,你希望根据某个键的值进行过滤:

$items = [
    ['id' => 1, 'name' => 'Alice', 'age' => 25],
    ['id' => 2, 'name' => 'Bob', 'age' => 30],
    ['id' => 3, 'name' => 'Charlie', 'age' => 25],
    ['id' => 4, 'name' => 'David', 'age' => 35]
];

$filteredItems = array_filter($items, function($item) {
    return $item['age'] == 25;
});

print_r($filteredItems);

PHP

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [age] => 25
        )

    [2] => Array
        (
            [id] => 3
            [name] => Charlie
            [age] => 25
        )
)

示例 2:过滤数组中某个值

假设你有一个简单的数值数组,你希望过滤出特定的值:

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$filteredNumbers = array_filter($numbers, function($number) {
    return $number % 2 == 0; // 过滤出偶数
});

print_r($filteredNumbers);

PHP

输出:

Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)

使用 array_column 和 array_keys 函数

如果你希望根据数组中某个键的值过滤,并且保留原来的键名,可以使用 array_column 和 array_keys 函数。

示例 3:过滤数组中某个键的值并保留键名

$items = [
    ['id' => 1, 'name' => 'Alice', 'age' => 25],
    ['id' => 2, 'name' => 'Bob', 'age' => 30],
    ['id' => 3, 'name' => 'Charlie', 'age' => 25],
    ['id' => 4, 'name' => 'David', 'age' => 35]
];

$ages = array_column($items, 'age');
$keys = array_keys($ages, 25);

$filteredItems = array_intersect_key($items, array_flip($keys));

print_r($filteredItems);

PHP

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [age] => 25
        )

    [2] => Array
        (
            [id] => 3
            [name] => Charlie
            [age] => 25
        )
)

使用 foreach 循环

如果你更喜欢使用循环来手动过滤数组,也可以这样做:

示例 4:使用 foreach 循环过滤数组

$items = [
    ['id' => 1, 'name' => 'Alice', 'age' => 25],
    ['id' => 2, 'name' => 'Bob', 'age' => 30],
    ['id' => 3, 'name' => 'Charlie', 'age' => 25],
    ['id' => 4, 'name' => 'David', 'age' => 35]
];

$filteredItems = [];
foreach ($items as $item) {
    if ($item['age'] == 25) {
        $filteredItems[] = $item;
    }
}

print_r($filteredItems);

PHP

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [age] => 25
        )

    [1] => Array
        (
            [id] => 3
            [name] => Charlie
            [age] => 25
        )
)

标签:
来源: