检查值是否设置到 PHP 数组的元素中

Check if value is set into PHP array's elements

我有以下名为 $users 的数组:

$users [2 elements]
0: 
(array) [4 elements]
id: (string) "5"
user_id: (null) 5
email: (string) "test@test.com"
activated: (integer) 0 

1: 
(array) [4 elements]
id: (string) "6"
user_id: (null) 6
email: (string) "test1@test.com"
activated: (integer) 1 

我想在 HTML 中显示一些东西,只有当数组的任何元素 activated 设置为 1 时。可以是全部,也可以只是一个。

我试过 if( in_array(['actived'] == 1, $users)) 但没有成功。

如何实现?

试试这个 if($users->activated == 1)

使用 array_column() 获取所有 activated 值并在其中搜索:

if (in_array(1, array_column($users, 'activated'), true))

您可以在循环中迭代数组时执行此操作

foreach ($users as $user) {
    if ($user['activated'] === 1) {
        // echo html here
    }
}

或挤在 html 标记内:

<?php foreach ($users as $user): ?>
    <?php if ($user['activated'] === 1): ?>
    <tr>
        <td><?php echo $user['email']; ?></td> // and others
    </tr>
    <?php endif; ?>
<?php endforeach; ?>

或者您可以使用 array_filter:

过滤掉里面的所有项目
$filtered_users = array_filter($users, function($user) {
    return $user['activated'] === 1; // get all user with activated key with value 1
});

当然,如果它来自mysql db,最好只使用WHERE子句:

SELECT id, user_id, email, activated FROM users WHERE activated = 1