0

First of all credits to the maker of the array search function. What I need is to make it filter multiple keys in array. The current function was only limited to search 1 key and value per use.

$arr = array(0 => array(id=>1,name=>"cat 1"),
         1 => array(id=>2,name=>"cat 2"),
         2 => array(id=>3,name=>"cat 1")
);

And below is the function(Credits to owner):

function search($array, $key, $value)
{
    $results = array();
    search_r($array, $key, $value, $results);
    return $results;
}

function search_r($array, $key, $value, &$results)
{
   if (!is_array($array)) {
      return;
}

if (isset($array[$key]) && $array[$key] == $value) {
    $results[] = $array;
}

foreach ($array as $subarray) {
    search_r($subarray, $key, $value, $results);
  }
}

If I use search($arr, 'name', 'cat 1') it will return:

array(0 => array(id=>1,name=>"cat 1"),
  1 => array(id=>3,name=>"cat 1")
);

But if I want it to filter by 'name' => 'cat 1' and 'id' => 1, it will only return:

array(0 => array(id=>1,name=>"cat 1")
);

But I need the function in accept dynamic filter parameter for I will use it over different multidimensional arrays. Any help would be deeply appreciated.

Edit:

What I have tried so far

public function search($array, $search)
{
    $results = array();
    foreach($search as $key => $value){
        $condition[] = 'isset($subarray["'.$key.'"]) && $subarray["'.$key.'"] == "'.$value.'"';
    }

    $filter = implode($condition, ' && ');

    foreach($array as $subarray){
        if ($filter) {
            $results[] = $subarray;
      }
    }

    return $results;
}

But I can't run $filter as php code. Please help!

1 Answer 1

1

Not the most optimized solution, but you can use array_filter in combination with array_intersect_assoc:

function search(array $array, array $search)
{
    return array_filter($array, function ($item) use ($search) {
        return array_intersect_assoc($search, $item) === $search;
    });
}

Here is working demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.