php 如果值匹配[重复],则从特定数组中获取值

roejwanj  于 2023-05-05  发布在  PHP
关注(0)|答案(1)|浏览(117)

此问题已在此处有答案

Split a comma-delimited string into an array?(8个回答)
Explode string on commas and trim potential spaces from each value(11个答案)
Explode Comma Separated Values with or without Spaces [duplicate](3个答案)
PHP preg_split remove commas and trailing white-space(3个答案)
How to split a string by commas in PHP [duplicate](3个答案)
2天前关闭。
如果电子邮件匹配,则从数组键['email']中获取值。
我想打印'特殊用户'在WordPress的评论,如果用户的电子邮件匹配数组键值。

$match_email = 'muskan2874@gmail.com, khushi7382@gmail.com';

$config = [
    'special_user' => [
        'muskan' => [
            'age' => '24',
            'email' => 'muskan2874@gmail.com'
        ],
        'khushi' => [
            'age' => '21',
            'email' => 'khushi7382@gmail.com'
        ]
    ]
];


foreach ($config as $name => $users) {
    foreach ($users as $author => $email) {
        if (in_array($email['email'], $match_email)) {
            echo 'Special User';
            break;
        }
    }
}

如果电子邮件与数组值匹配,则打印“特殊用户”。

relj7zay

relj7zay1#

它不起作用,因为你没有传递一个数组给这个:
in_array($user_data['email'], $match_email)
您需要将$match_email转换为具有explode()的数组。

<?php

$match_email = explode(', ', 'muskan2874@gmail.com, khushi7382@gmail.com');

$config = [
    'special_user' => [
        'muskan' => [
            'age' => '24',
            'email' => 'muskan2874@gmail.com'
        ],
        'khushi' => [
            'age' => '21',
            'email' => 'khushi7382@gmail.com'
        ]
    ]
];


foreach ($config as $name => $users) {
    foreach ($users as $author => $user_data) {
        if (in_array($user_data['email'], $match_email)) {
            echo 'Special User';
            break;
        }
    }
}

如果可能的话,您也可以首先使用数组:

<?php

$match_email = ['muskan2874@gmail.com', 'khushi7382@gmail.com'];

$config = [
    'special_user' => [
        'muskan' => [
            'age' => '24',
            'email' => 'muskan2874@gmail.com'
        ],
        'khushi' => [
            'age' => '21',
            'email' => 'khushi7382@gmail.com'
        ]
    ]
];


foreach ($config as $name => $users) {
    foreach ($users as $author => $email) {
        if (in_array($email['email'], $match_email)) {
            echo 'Special User';
            break;
        }
    }
}

相关问题