繁体   English   中英

使用 php 检查键是否在多维数组中具有值

[英]Check if a key has a value in a multidimensional array with php

我将 SQL 请求的结果放在一个数组中以获得类似:

Array (
[0] => Array ( [id] => 253 [mother_id] => 329 )
[1] => Array ( [id] => 329 [mother_id] => 210 )
[2] => Array ( [id] => 293 [mother_id] => 329 )
[3] => Array ( [id] => 420 [mother_id] => 293 )
)

我想在 ID 为 329 的人的个人资料页面中显示她的孩子的列表,所以这里是 ID 253 和 293。我的数组中有更多值,例如人名。 如何获取每个将“329”作为“mother_id”的人的 ID、姓名等?

我认为这与 array_key_exists() 有关,但经过多次搜索后我自己没有找到。 请帮忙:)

编辑

我的代码如下所示:

$request = $database->prepare("SELECT * FROM users");
$request->execute();

$result = $request->fetchAll();
print_r($result); // The code above

$usersWithMother = array_filter(
  $result,
  function (array $user) {
      return $user['mother_id'] === 329;
  }
);
print_r($userWithMother); // Array ()

array_filter是你的朋友:

$usersWithMother = array_filter(
        $users,
        function (array $user) {
            return (int)$user['mother_id'] === 329;
        }
    );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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