我有这个ff。关联数组$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 回答
有只小跳蛙
TA贡献1824条经验 获得超8个赞
您可以使用 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');
- 1 回答
- 0 关注
- 101 浏览
添加回答
举报
0/150
提交
取消