我对php搜索关联数组有疑问

时间:2019-07-01 08:49:41

标签: php arrays

我有这个ff。 assoc数组

$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'],
        ],
    ],
]

我有这段代码,但这只搜索第一级数组。

  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;
    }

我要搜索的是此数组中的所有键,这些键将导致所有与键相关联的数组,如:

searchItemsByKey($array, 'hrm');

这将返回:

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

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用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