0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

連想配列からキーと値を指定して抽出する

Last updated at Posted at 2021-08-05

データベースからレコードを取得した際、大体は以下のような二次元の連想配列である。
この時、あるキーにおいて指定の値を持つものを抽出したいことがある。

元データ
$array = [
    0 => ['id' => 1, 'blood' => 'A', 'name' => 'yamada'],
    1 => ['id' => 2, 'blood' => 'B', 'name' => 'tanaka'],
    2 => ['id' => 3, 'blood' => 'O', 'name' => 'satake'],
    3 => ['id' => 4, 'blood' => 'B', 'name' => 'murata'],
    4 => ['id' => 5, 'blood' => 'B', 'name' => 'takeda']
];

例えば、キー blood の値が B のものを抽出する場合は以下。1

$new_array = array_filter($array, fn($a) => $a['blood'] === 'B');

print_r($new_array);
結果
Array
(
    [0] => Array
        (
            [id] => 2
            [blood] => B
            [name] => tanaka
        )

    [1] => Array
        (
            [id] => 4
            [blood] => B
            [name] => murata
        )

    [2] => Array
        (
            [id] => 5
            [blood] => B
            [name] => takeda
        )
)
  1. コメントにて、より簡潔な記述を教えていただきましたので修正しました。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?