PHP: Filter array

前端 未结 1 660
猫巷女王i
猫巷女王i 2020-12-11 09:35

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

For example, I have this 2D array:

[
    [\'UK\', \'12\', \'Sus\',         


        
相关标签:
1条回答
  • 2020-12-11 10:03

    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);
    
    0 讨论(0)
提交回复
热议问题