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

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;
}

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.

I vaguely remember implementing this type of functionality many years ago:

http://forums.devnetwork.net/viewtopic.php?t=47855

Look to the sortRows() and _quickSort() methods

HTH

Do it:

$arr =  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" => "this_week" ),
  4 => array ( "type" => "blah2", "category" => "cat2","exp_range" => "next week" ),
);

function filter(array $arr,array $params){
  $out = array();
  foreach($arr as $key=>$item){
     $diff = array_diff_assoc($item,$params);

     if (count($diff)==1) // if count diff == 1 - Ok
        $out[$key] = $item;
 }
 return $out;
}

$out = filter($arr,array("type" => "blah1", "category" => "cat1"));

echo '<pre>';
print_r($out);
echo '</pre>';

// output

Array
(
  [1] => Array
     (
        [type] => blah1
        [category] => cat1
        [exp_range] => this_week
    )

[3] => Array
    (
        [type] => blah1
        [category] => cat1
        [exp_range] => this_week
    )

)

The issue is the fact that your function will return the key of every array that contains "cat1" or "blah1". You can fix it with array_unique():

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;
}

$bigarray = array(
array('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'this_week'),
array('type' => 'blah1', 'category' => 'cat2', 'exp_range' => 'next week'),
array('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'next week'),
array('type' => 'blah2', 'category' => 'cat2', 'exp_range' => 'this_week')
);

$result = array_searcher(array('cat1','blah1'), $bigarray);
$unique_result = array_unique($result);
print_r($unique_result);

so lets assign your base array to a variable:

$array = 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 )
)

and lets's have an array containing our filter:

$filter = array(
'type' => 'blah1'
'category' => 'cat1'
)

then we start our filtering script

foreach ($array as $key => $row){
  $i = 0;
  foreach ($filter as $filterKey => $filterValue){
    if ($row[$filterKey] != $filterValue){
      $i++;
    }}
  if ($i == 0){
    $filteredArray[] = $row;
}}

if $i still equals 0 after the row is tested against our filter, we add the row to our filtered array