PHP:筛选器数组 [英] PHP: Filter array

查看:66
本文介绍了PHP:筛选器数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除数组中不满足某些条件的所有元素.

I would like to delete all elements from an array that don't meet some condition.

例如,我有这个2D数组:

For example, I have this 2D array:

[
    ['UK', '12', 'Sus', 'N'],
    ['UK', '12', 'Act', 'Y'],
    ['SQ', '14', 'Act', 'Y'],
    ['CD', '12', 'Act', 'Y']
]

,我想删除所有与此格式不匹配的行:

and I would like to delete all rows that don't match this format:

['UK' or 'CD', '12', Any Value, 'Y']

将这个过滤后的数组留给我:

leaving me with this filtered array:

[
    ['UK', '12', 'Act', 'Y'],
    ['CD', '12', 'Act', 'Y']
]

我该怎么做?

推荐答案

使用 array_filter .它允许您通过提供回调对每个项目执行检查.在该回调函数中,为符合您的条件的项目返回true. array_filter返回一个数组,其中删除了所有不符合您的条件的项目.

Use array_filter. It allows you to perform a check on each item by providing a callback. In that callback function, return true for items that match your criteria. array_filter returns an array with a all the items that don't match your criteria removed.

例如,您的示例数组可以像这样过滤:

For instance, your example array could be filtered like this:

$array = [
    ['UK', '12', 'Sus', 'N'],
    ['UK', '12', 'Act', 'Y'],
    ['SQ', '14', 'Act', 'Y'],
    ['CD', '12', 'Act', 'Y']
];

$filtered_array = array_filter($array, function ($item) {
    return count($item) >= 4 &&
           ($item[0] == 'UK' || $item[0] == 'CD') &&
           $item[1] == '12' &&
           $item[3] == 'Y';
});

print_r($filtered_array);

这篇关于PHP:筛选器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆