Search code examples
phparraysmultidimensional-arrayconditional-statementsfiltering

Search for string in 2nd level keys of a 3d array; upon match, check if 1st level key equals specific string


$display_name = get_the_author_meta('display_name');

$config = array(
    'premium_users' => [
        'rahat' => [
            'color' => 'blue',
            'icon' => 'fa-check-circle'
        ],
        'jondoe' => [
            'color' => 'orange',
            'icon' => 'fa-check'
        ]
    ],
    'secondary_users' => [
        'smith' => [
            'color' => 'purple',
            'icon' => 'fa-check'
        ]
    ],
);


$verified_author = "";
foreach ($config as $group => $users) {
    foreach ($users as $author => $data) {

        if ($author === $display_name && $group === 'premium_users') {
            $verified = '<'.$wrap.' class="i-'.$data['icon'].' '.
            $data['color'].'"></'.$wrap.'>';
        echo    $verified_author;
            break;
        }

    }

if($group === 'premium_users') {
    echo $group;
}

I want to Echo all users list with premium_user if ['premium_users'] defined.

Please modify this function. Get value from config if defined [premium_user] then echo all users that have premium or secondary user.


Solution

  • Loop over the first level's elements and use the same lookup technique with isset().

    $verified = '';
    foreach ($config as $level => $users) {
        if (isset($users[$display_name])) {
            $verified = sprintf(
                '<i class="%s %s"></i>',
                $users[$display_name]['icon'],
                $users[$display_name]['color']
            );
            if ($level === 'premium_users') {
                echo implode(', ', array_keys($config[$level])); // print premium names
            }                
            break;
        }
    }