I have been searching everywhere for this and i not sure something like this can be done. but i hope some one can point me in the right direction.
I am getting a multidimensional array from mysql. I need to filter this array, so i am using the following code
$filter = new MultipleKeyValueFilter(array(
'sex' => '1',
'age' => '4'
));
print_r(array_filter($ads_array, array($filter, 'filter')));
I have the filter values set as you can see, but i need these values to do something like this
$filter = new MultipleKeyValueFilter(array(
'sex' => '1' or '0',
'age' => '4'
));
echo "Filtered by multiple fields
";
print_r(array_filter($ads_array, array($filter, 'filter')));
As you can see in the code above, i want to keep both of them in the array. The field can have 1 or 0 and both is good. But when i try this i get nothing. So it seems i can't use or and also not ||.
How should i go about this issue. How can i have it accept both values as a good result?
The other pieces of code i am using are these
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;
}
}
class MultipleKeyComparator implements Comparator {
protected $keys;
public function __construct($keys) {
$this->keys = $keys;
}
I hope i make a little sense here.
The reason it is not working is because when you say:
'sex' => '1' or '0',
that gets interpreted an in-line conditional and you wind up with
'sex' => true,
If you want your MultipleKeyValueFilter
to do what you want, you're going to have to change both your criteria array and your filter class. You'll want to pass something like:
'sex' => ['1', '0'], //1 and 0 are acceptable values
and rewrite your comparator to something like:
public function filter($item) {
foreach ($this->kvPairs as $key => $value) {
if(is_array($value) {
$match = false;
foreach($value as $v) {
$match = ($item[$key] === $v);
if($match) {
break; //If we find one match in our array, we can stop looking
}
}
} else {
$match = ($item[$key] === $value);
}
if(!$match) {
return false; //Any failure to match can stop immediately
}
}
return true; //If we get here, then we didn't fail to match any criteria
}