Search code examples
phparraysmultidimensional-arrayarray-intersect

PHP Array_intersect on multidimensional array with unknown number of keys


I'm trying to make advanced search filters in an application that holds resources (people). I've got all the results in 1 multidimensional array. A user of the application can search for the persons Job title, skills, work field and country.

I've already made the part where I look up the people that meet the criteria given by the user. These results are stored in a multidimensional array. If the user is looking for someone with a specific resource with a job title and a specific skill the return value is this:

$realfilters = array(2) {
["resourcesWithJobtitle"]=> array(6) {
   [0]=> string(1) "1"
   [1]=> string(2) "48"
   [2]=> string(2) "88"
}
["resourcesWithSkill"]=> array(9) {
   [0]=> string(1) "4"
   [1]=> string(1) "8"
   [2]=> string(1) "48"
   [3]=> string(2) "50"
}

When the user also looks for a work field this is added to the result:

["resourcesWithWorkfield"]=> array(3) {
   [0]=> string(2) "48"
   [1]=> string(2) "96"
   [2]=> string(2) "97"
}

I need to know which resources meet all dimensions of the array so I can display them. (So in this example I need an array with just 1 value: 48). I think I need to use array_intersect but can't seem to get it right.


Solution

  • One of the possible solutions: you may first extract() the $realfilters array values to variables, and then apply the array_intersect() to them. But this solution is applicable only if there are not many possible filters.

    Another one and probably the best solution would be to intersect in a loop, something like:

    $res_arr = array_shift($realfilters);
    foreach($realfilters as $filter){
         $res_arr = array_intersect($res_arr, $filter);
    }