0

I have this ff. assoc array

$array = [
    'school' => [
        'college' => [
            'nursing' => ['n1a', 'n2a', 'n3a', 'n4a'],
            'hrm' => ['h1a', 'h2a', 'h3a', 'h4a'],
            'tourism' => ['t1a', 't2a', 't3a', 't4a'],
            'it' => ['i1a', 'i2a', 'i3a', 'i4a'],
        ],
        'senior' => [],
    ],
    'business' => [
        'office' => [
            'dep1' => ['team1', 'team2'],
            'dep2' => ['team1', 'team2'],
            'dep3' => ['team1', 'team2'],
            'dep4' => ['team1', 'team2'],
        ],
    ],
]

And I have this code, but this only search first level array.

  function searchItemsByKey($array, $key) {
       $results = array();

          if (is_array($array))
          {

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

            foreach ($array as $sub_array){
                $results = array_merge($results, $this->searchItemsByKey($sub_array, $key));
            }
          }

         return  $results;
    }

All I want is to search all keys in this array that will result all arrays associated with keys like:

searchItemsByKey($array, 'hrm');

That will return:

['h1a', 'h2a', 'h3a', 'h4a']

Thanks.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
kikeyg
  • 3
  • 1

1 Answers1

2

You can use array_walk_recursive,

$result = [];
$search = "hrm";
function searchItemsByKey($array, $key)
{
    $retArr = [];
    if (is_array($array)) {
        if (!empty($array[$key])) {
            return $array[$key];
        }
        foreach ($array as $val) {
            $retArr = array_merge($retArr, searchItemsByKey($val, $key));
        }
    }
    return $retArr;
}
$temp = searchItemsByKey($array, 'hrm');

Demo.

Rahul
  • 18,271
  • 7
  • 41
  • 60
  • Notice this will take only the last recurrence of the key - the OP want all of them (as he does `result[] = ...` or `array_merge`) – dWinder Jul 01 '19 at 09:00
  • 1
    Yes I am on correcting answer, I thought it wil give every key, but its sticking to leaf nodes. – Rahul Jul 01 '19 at 09:01