Search code examples
phparraysmultidimensional-arrayphp-5.5

Search multi dimensional array returning multiple results


I am trying to search a multi dimensional array, but the search only returns the first occurrence.

I have a multi dimensional array $planned_housek:

Array
(
    [0] => Array
        (
            [id] => 14
            [title] => Titel 10
            [ruletext] => Regel 10
            [room] => 101
            [roomid] => 43
        )

    [1] => Array
        (
            [id] => 14
            [title] => Titel 10
            [ruletext] => Regel 10
            [room] => 102
            [roomid] => 42
        )

    [2] => Array
        (
            [id] => 14
            [title] => Titel 10
            [ruletext] => Regel 10
            [room] => 103
            [roomid] => 41
        )

    [3] => Array
        (
            [id] => 14
            [title] => Titel 10
            [ruletext] => Regel 10
            [room] => 104
            [roomid] => 44
        )

    [4] => Array
        (
            [id] => 14
            [title] => Titel 10
            [ruletext] => Regel 10
            [room] => 105
            [roomid] => 45
        )

    [5] => Array
        (
            [id] => 7
            [title] => TItel 3
            [ruletext] => Regel 3
            [room] => 101
            [roomid] => 43
        )

    [6] => Array
        (
            [id] => 13
            [title] => Titel 9
            [ruletext] => Regel 9
            [room] => 101
            [roomid] => 43
        )
)

When I search it with:

$planned_tasks = array_search($bkng_room, array_column($planned_housek, 'roomid'));

It returns the first occurrence of the $bkng_room.

Do I have to use a for/foreach to get an array of matches? Or is there a more elegant solution (PHP 5.5)?

I found this question, but the answer doesn't seem the most elegant solution: How to search a multidimensional array to return multiple keys. Neither does this one: Search multidimensional array for value and return new array

In the docs on array_search I found:

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

But I'm not sure how to implement this in my code.


Solution

  • Hope, This function is what you want !!

    function array_search_inner ($array, $attr, $val, $strict = FALSE) {
      if (!is_array($array))
          return FALSE;
       foreach ($array as $key => $inner) {
          if (!is_array($inner))
               return FALSE;
          if (!isset($inner[$attr])) 
               continue;
          if ($strict) {
          if ($inner[$attr] === $val) 
               return $key;
        } else {
          if ($inner[$attr] == $val) return $key;
        }
      }
      return NULL;
    }
    
    // Example usage
    $key = array_search_inner($array, 'id', 6);
    print_r($key);