我有一个像这样的数组
protected $aPermissions = [
'read' => [
'show'
],
'update' => [
'edit',
'editProfilePicture'
]
];
,我想通过一个可能在子数组中找到的值来获取子数组的数组键(“读取”,“更新”)。因此,搜索“ edit”将返回“ update”,而“ show”将返回“ read”。
我尝试了PHP的array_search函数(也是递归地循环执行),但是没有设法使它起作用。实现我想要的最佳方法是什么?
答案 0 :(得分:1)
一个选项是使用array_filter
遍历数组,并且仅包括包含$search
字符串的子数组。使用array_keys
提取密钥。
$aPermissions = [
'read' => [
'show'
],
'update' => [
'edit',
'editProfilePicture'
]
];
$search = 'edit';
$result = array_keys(array_filter($aPermissions, function( $o ) use ( $search ) {
return in_array( $search, $o );
}));
$result
将导致:
Array
(
[0] => update
)
答案 1 :(得分:1)
假设键在第一级,值在第二级,您可以执行以下操作:
$innerKeys = [
"show",
"edit"
];
$output = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
foreach ($value as $innerKey => $innerValue) {
if (isset($innerKeys[$innerKey])) $output[$innerKey] = $key;
}
}
}
如果您的问题更复杂,则需要向我们提供其他信息。
答案 2 :(得分:1)
您可以使用array_walk
和in_array
来获得key
,没有返回类型数组,只是简单的键名,否则为null
$aPermissions = [
'read' => [
'show'
],
'update' => [
'edit',
'editProfilePicture'
]
];
$searchAction = 'show';
$keyFound = '';
array_walk($aPermissions, function($value, $key) use ($searchAction, &$keyFound){
in_array($searchAction, $value) ? ($keyFound = $key) : '';
});
echo $keyFound;
输出
read
答案 3 :(得分:0)
看看时间不使用PHP,但是此代码应该可以使用!!
<?php
$a = [
'read' => [
'show'
],
'update' => [
'edit',
'editProfilePicture'
]
];
$tmp = array_keys($a);
$searchterm = 'edit';
for($x =0 ; $x < count($tmp); $x++){
if(in_array($searchterm,$a[$tmp[$x]])){
echo $tmp[$x];
}
}