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 1 year has passed since last update.

PHP array_column 連想配列の値を取得

Posted at

array_column()

例として使う連想配列
$hoge = [
    0 => [ 'id' => 100, 'color' => 'red', 'team' => 'A'],
    1 => [ 'id' => 200, 'color' => 'blue', 'team' => 'B'],
    2 => [ 'id' => 300, 'color' => 'green', 'team' => 'C' ],
    3 => [ 'id' => 400, 'color' => 'yellow', 'team' => 'D' ],
];

特定の要素だけ取り出す

$hoge = [
    0 => [ 'id' => 100, 'color' => 'red', 'team' => 'A'],
    1 => [ 'id' => 200, 'color' => 'blue', 'team' => 'B'],
    2 => [ 'id' => 300, 'color' => 'green', 'team' => 'C' ],
    3 => [ 'id' => 400, 'color' => 'yellow', 'team' => 'D' ],
];

var_dump(array_column($hoge, 'id'));

// array(size=4)
//  0=>int100
//  1=>int200
//  2=>int300
//  3=>int400

解説
array_column()
第1引数 に「対象の配列」
第2引数 に「取り出す要素のキー名」
を指定すると 「キーのみの配列」 が取得できる。
例の場合はidのみの配列が取得できる。

特定の要素をキーに、特定の要素を値にした配列を取得

$hoge = [
    0 => [ 'id' => 100, 'color' => 'red', 'team' => 'A'],
    1 => [ 'id' => 200, 'color' => 'blue', 'team' => 'B'],
    2 => [ 'id' => 300, 'color' => 'green', 'team' => 'C' ],
    3 => [ 'id' => 400, 'color' => 'yellow', 'team' => 'D' ],
];

var_dump(array_column($hoge, 'color', 'team'));

// array(size=4)
//  'A'=>string'red'(length=3)
//  'B'=>string'blue'(length=4)
//  'C'=>string'green'(length=5)
//  'D'=>string'yellow'(length=6)

解説
array_column()
第1引数 に対象の対象の配列
第2引数 に値にしたい要素
第3引数 にキーにしたい要素
を指定すると 「第3引数がキーで第2引数が値の配列」 が取得できる。
例の場合はteamがキーでcolorが値の配列が取得できた。
 
 
 
参考にした記事
https://qiita.com/harukasan/items/a0773aef27d838852e44

0
0
0

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?