【问题标题】:Check if value is set into PHP array's elements检查值是否设置到 PHP 数组的元素中
【发布时间】:2020-09-11 05:28:40
【问题描述】:

我有一个名为$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 

只有当数组的任何元素将activated 设置为 1 时,我才想在 HTML 中显示某些内容。可以是全部,也可以是唯一。

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

我如何做到这一点?

【问题讨论】:

    标签: php arrays element


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以在循环中迭代数组时这样做

      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
      

      【讨论】:

      • 谢谢!在我的控制器中执行一个循环并导出一个变量(几乎是你的第一个解决方案),我设法在阅读它之前修复它。然后,在我看来,我只是检查该 var 是否已设置并显示我想要的内容。
      【解决方案3】:

      试试这个if($users-&gt;activated == 1)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多