user10984218
user10984218

Reputation: 83

2D array - search by value and return index of array

I've an array like

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

and I want to get the array key for the sub-array ('read', 'update') by a value to possibly find within the sub-array. So searching for 'edit' would return 'update', whereas 'show' would return 'read'.

I tried PHP's array_search function (also recursively, in a loop), but didn't manage to get this to work. What's the best approach to achieve what I want?

Upvotes: 1

Views: 57

Answers (4)

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can use array_walk and in_array to get the key, there is no return type array it's just simple key name else 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;

Output

read

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76905

Assuming that the keys are on the first level and the values are in the second level you could do something like this:

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

If your problem is more complex, then you will need to give us additional information.

Upvotes: 1

Varun
Varun

Reputation: 1946

Look time not used PHP, but this code should work!!

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

}

Upvotes: 0

Eddie
Eddie

Reputation: 26854

One option is using array_filter to loop thru the array and only include sub array that contains the $search string. Use array_keys to extract the 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 will result to:

Array
(
    [0] => update
)

Upvotes: 2

Related Questions