phparrayssearchkeyarray-key-exists

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 :

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

I think there is something to do with array_key_exists() but I didn't find by myself after many searches. 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 ()

Solution

  • array_filter is your friend:

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