dongyoucha0645 2014-01-23 21:30
浏览 82
已采纳

使用多个值过滤和排序多维数组

I have a large multidimensional array something like the below:

Array( 
    [1] => Array ( [type] => blah1 [category] => cat1 [exp_range] => this_week ) 
    [2] => Array ( [type] => blah1 [category] => cat2 [exp_range] => next week ) 
    [3] => Array ( [type] => blah1 [category] => cat1 [exp_range] => next week ) 
    [4] => Array ( [type] => blah2 [category] => cat2 [exp_range] => this_week )
)

I want to be able to filter this array with multiple filters.
eg. filtering where category = cat1 and type = blah1 would return array 1 and 3.

I have the below function that would return keys 1,2,3 which is incorrect as array 2 doesnt have both cat1 and blah1

Can anyone see what I need to do to get this working?

Also would it be possible to incorporate sortin in this function, if so how?

function array_searcher($needles, $array) { 
    foreach ($needles as $needle) {
        foreach ($array as $key => $value) { 
           foreach ($value as $v) { 
            if ($v == $needle) { 
                $keys[] = $key; 
            } 
           }
        }
    }
    return $keys;
}
  • 写回答

5条回答 默认 最新

  • duanduan1993 2014-01-23 21:48
    关注

    I decided to rewrite my answer to accommodate both filtering and sorting. I took a heavily object oriented approach to solving this problem, which I will detail below.

    You can see all of this code in action at this ideone.com live demonstration.


    The first thing I did was define two interfaces.

    interface Filter {
        public function filter($item);
    }
    
    interface Comparator {
        public function compare($a, $b);
    }
    

    As their names suggest, Filter is used for filtering, and Comparator is used for comparing.

    Next, I defined three concrete classes that implements these interfaces, and accomplish what I wanted.

    First is KeyComparator. This class simply compares the key of one element to the key of another element.

    class KeyComparator implements Comparator {
        protected $direction;
        protected $transform;
        protected $key;
    
        public function __construct($key, $direction = SortDirection::Ascending, $transform = null) {
            $this->key = $key;
            $this->direction = $direction;
            $this->transform = $transform;
        }
    
        public function compare($a, $b) {
            $a = $a[$this->key];
            $b = $b[$this->key];
    
            if ($this->transform) {
                $a = $this->transform($a);
                $b = $this->transform($b);
            }
    
            return $a === $b ? 0 : (($a > $b ? 1 : -1) * $this->direction);
        }
    }
    

    You can specify a sort direction, as well as a transformation to be done to each element before they are compared. I defined a helped class to encapsulate my SortDirection values.

    class SortDirection {
        const Ascending = 1;
        const Descending = -1;
    }
    

    Next, I defined MultipleKeyComparator which takes multiple KeyComparator instances, and uses them to compare two arrays against each other. The order in which they are added to the MultipleKeyComparator is the order of precedence.

    class MultipleKeyComparator implements Comparator {
        protected $keys;
    
        public function __construct($keys) {
            $this->keys = $keys;
        }
    
        public function compare($a, $b) {
            $result = 0;
    
            foreach ($this->keys as $comparator) {
                if ($comparator instanceof KeyComparator) {
                    $result = $comparator->compare($a, $b);
    
                    if ($result !== 0) return $result;
                }
            }
    
            return $result;
        }
    }
    

    Finally, I created MultipleKeyValueFilter which is meant to filter an array based on an array of key/value pairs:

    class MultipleKeyValueFilter implements Filter {
        protected $kvPairs;
    
        public function __construct($kvPairs) {
            $this->kvPairs = $kvPairs;
        }
    
        public function filter($item) {
            $result = true;
    
            foreach ($this->kvPairs as $key => $value) {
                if ($item[$key] !== $value)
                    $result &= false;
            }
    
            return $result;
        }
    }
    

    Now, given the input array (Notice I rearranged them a bit to make the sorting obvious):

    $array = array (
        '1' => array ('type' => 'blah2', 'category' => 'cat2', 'exp_range' => 'this_week' ),
        '2' => array ('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'this_week' ),
        '3' => array ('type' => 'blah1', 'category' => 'cat2', 'exp_range' => 'next_week' ),
        '4' => array ('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'next_week' )
    );
    

    Sorting can be achieved by doing the following:

    $comparator = new MultipleKeyComparator(array(
        new KeyComparator('type'),
        new KeyComparator('exp_range')
    ));
    
    usort($array, array($comparator, 'compare'));
    
    echo "Sorted by multiple fields
    ";
    print_r($array);
    

    Filtering can be achieved by doing the following:

    $filter = new MultipleKeyValueFilter(array(
        'type' => 'blah1'
    ));
    
    echo "Filtered by multiple fields
    ";
    print_r(array_filter($array, array($filter, 'filter')));
    

    At this point I've given you a great deal of code. I'd suggest that your next step is to combine these two pieces into a single class. This single class would then apply both filtering and sorting together.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用