PHP 4级多维关联数组搜索


大家好,我有一个多维关联数组,我想在数组中搜索。
public static function userAccessArray()
{
return array(
array(
'title' => 'General',
'access' => array(
array('header' => 'Configuration' ,'link' => 'configuration', 'id' => 'configuration'),
array('header' => 'Colleges'      ,'link' => 'college', 'id' => 'college'),
array('header' => 'Periods'       ,'link' => 'period', 'id' => 'period'),
array('header' => 'School'        ,'link' => 'school', 'id' => 'school'),
array('header' => 'User Accounts' ,'link' => 'user', 'id' => 'user'),
array('header' => 'Audit Log'     ,'link' => 'configuration/auditlog', 'id' => 'auditlog')
)
),
array(
'title' => 'Offerings',
'access' => array(
array('header' => 'Programs'    ,'link' => 'program', 'id' => 'program'),
array('header' => 'Departments' ,'link' => 'department', 'id' => 'department'),
array('header' => 'Curriculum'  ,'link' => 'curriculum', 'id' => 'curriculum'),
array('header' => 'Instructors' ,'link' => 'instructor', 'id' => 'instructor'),
array('header' => 'Rooms'       ,'link' => 'room', 'id' => 'room'),
array('header' => 'Sections'    ,'link' => 'section', 'id' => 'section'),
array('header' => 'Subjects'    ,'link' => 'subject', 'id' => 'subject')
)
)

))

我想在LINK列中搜索,如果它存在,我想返回TITLE和数组中的其余访问值。

public static function searchUSerAccess($array, $val, $column)
{
$arr = [];
foreach ($array as $key => $value) {
foreach ($value['access'] as $k => $v) {
$keyres = array_search($val, array_column($v, $column));
}
}
}
return Helpers::searchUSerAccess(Helpers::userAccessArray(), 'college', 'link');

使用array_search()并不真正适合您的用例,因为根据文档,它是

在数组中搜索给定值,如果成功,则返回第一个对应的键

array_search()更多地用于数组中离散值的值列表,但我们对已知的特定键的值感兴趣,因此这不会返回任何感兴趣的信息。相反,我们可以迭代数组和子数组,并检查等式:

public static function searchUSerAccess($array, $val, $column)
{
// Loop through the top level array.
foreach ($array as $value) {
// Each iteration gives us
// $value = array('title' => '…', 'access' => array(…))
// Go through the 'access' element arrays, for a particular column
// and value.
foreach ($value['access'] as $access) {
// Each iteration gives us
// $access = array('header' => '…', 'link' => '…', 'id' => '…')

// Check the value of the column we are interested in.
if ($access[$column] === $val) {
// If found, give back a merge of array members we
// are interested in.
return [
'title' => $value['title'],
...$access,
];
}
}
}
}

这将为您的示例提供以下内容:

var_dump(Helpers::searchUSerAccess(Helpers::userAccessArray(), 'college', 'link'));
// array(4) {
//   ["title"]=>
//   string(7) "General"
//   ["header"]=>
//   string(8) "Colleges"
//   ["link"]=>
//   string(7) "college"
//   ["id"]=>
//   string(7) "college"
// }

最新更新