使用php检查键是否在多维数组中具有值 [英] Check if a key has a value in a multidimensional array with php

查看:80
本文介绍了使用php检查键是否在多维数组中具有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将SQL请求的结果放入数组中,以获得类似的内容:

I put the result of a SQL request in an array to get something like :

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"身份的人的ID,姓名等...作为"mother_id" ?

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. How can I get the id, name, etc... of every people who have "329" as "mother_id" ?

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

I think there is something to do with array_key_exists() but I didn't find by myself after many searches. Please help :)

我的代码如下:

$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;
        }
    );

这篇关于使用php检查键是否在多维数组中具有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆