简体   繁体   English

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

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

I put the result of a SQL request in an array to get something like:我将 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 )
)

I want to display in the profil page of the person with the ID 329 a list of her children, so here the ID 253 and 293. There are more values in my array such the name of the person.我想在 ID 为 329 的人的个人资料页面中显示她的孩子的列表,所以这里是 ID 253 和 293。我的数组中有更多值,例如人名。 How can I get the id, name, etc... of every people who have "329" as "mother_id"?如何获取每个将“329”作为“mother_id”的人的 ID、姓名等?

I think there is something to do with array_key_exists() but I didn't find by myself after many searches.我认为这与 array_key_exists() 有关,但经过多次搜索后我自己没有找到。 Please help:)请帮忙:)

EDIT编辑

My code looks like this:我的代码如下所示:

$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 is your friend: 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