简体   繁体   中英

check in_array for nested array

I have an array in this format, and I want to check if a var is in the array from any of the keys link

    $nav = array(
        'Account Settings' => array(
            'icon' => 'fa-cog',
            'Account Settings' => array(
                'link' => '/voip/settings?seq='.$seq,
                'icon' => 'fa-cog',
            ),
            'Provisioning' => array(
                'link' => '/voip/provisioning?seq='.$seq,
                'icon' => 'fa-wrench',
            ),
            'E999 Data' => array(
                'link' => '/voip/e999?seq='.$seq,
                'icon' => 'fa-life-ring',
            ),
            'Delete Account' => array(
                'link' => '/voip/delete?seq='.$seq,
                'icon' => 'fa-trash',
            ),
        ),
        'Mailboxes' => array(
            'link' => '/voip/mailboxes?seq='.$seq,
            'icon' => 'fa-envelope',
        ),
        'Telephone Numbers' => array(
            'link' => '/voip/numbers?seq='.$seq,
            'icon' => 'fa-hashtag',
        ),
    );

I tried if(in_array($_GET["nav"], $nav) but it doesn't pick up the nested values

Is there a way to do this?

Since you say the value is in link key then you can use array_column to isolate the link items.

if(in_array($_GET["nav"], array_column($nav['Account Settings'], "link")) || in_array($_GET["nav"], array_column(array_slice($nav, 1), "link"))){

This will first look at all link items in account settings, then slice out account settings and look at the other two subarrays for link items.

Test it here:
https://3v4l.org/pP2Nk

There's no readymade function to do that. Let's say you have:

$key = 'link';
$value = '/voip/e999?seq=' . $seq;
// and $nav your multidimensionnal array

You can write your own recursive function:

function contains_key_value_multi($arr, $key, $value) {
    foreach ($arr as $k => $v) {
        if ( is_array($v) && contains_key_value_multi($v, $key, $value) ||
             $k === $key && $v === $value )
            return true;
    }
    return false;
}

var_dump(contains_key_value_multi($nav, $key, $value));

You can use the spl classes to be able to loop over leafs of your multidimensionnal array. This time you don't need a recursive function:

$ri = new RecursiveIteratorIterator(new RecursiveArrayIterator($nav));

function contains_key_value($arr, $key, $value) {
    foreach ($arr as $k => $v) {
        if ( $k === $key && $v === $value ) 
            return true;
    }
    return false;
}

var_dump(contains_key_value($ri, $key, $value));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM