2D数组-按值搜索并返回数组的索引

时间:2019-04-27 15:58:04

标签: php arrays

我有一个像这样的数组

protected $aPermissions = [
    'read' => [
        'show'
    ],
    'update' => [
        'edit',
        'editProfilePicture'
    ]
];

,我想通过一个可能在子数组中找到的值来获取子数组的数组键(“读取”,“更新”)。因此,搜索“ edit”将返回“ update”,而“ show”将返回“ read”。

我尝试了PHP的array_search函数(也是递归地循环执行),但是没有设法使它起作用。实现我想要的最佳方法是什么?

4 个答案:

答案 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_walkin_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];
    }

}
相关问题