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.

多次元配列から特定の値を取り出す方法

Posted at

routeが'love'の配列のnameの値を取得したいとする。

$genres = [
  ['route' => 'jobs', 'name' => '仕事'],
  ['route' => 'life', 'name' => '日常'],
  ['route' => 'relationship', 'name' => '人間関係'],
  ['route' => 'dozi', 'name' => 'どじ'],
  ['route' => 'shame', 'name' => '恥'],
  ['route' => 'school', 'name' => '学校'],
  ['route' => 'love', 'name' => '恋愛'],  // ここのnameの値を取得したい!
  ['route' => 'marriage', 'name' => '結婚生活'],
  ['route' => 'game', 'name' => 'ゲーム'],
  ['route' => 'disease', 'name' => '病気'],
  ['route' => 'heart', 'name' => '心'],
];

// まず'route'の値だけの配列を作成する。
$genreRoutes = array_column($genres, 'route');
// 結果 $genreRoutes = ['jobs', 'life', 'relationship', .....];

// $genreRouteにおける'love'のインデックスを取得する。
$index = array_search('love', $genreRoutes);
// 結果 $index = 6;

// これで取得できる。
$genre_name = $genres[$index]['name'];
//結果 $genre_name = '恋愛';

全部繋げて書くと、

$genre_name = $genres[array_search('love', array_column($genres, 'route'))]['name'];
// 結果 $genre_name = '恋愛';

これ以外に方法ってあるんですかね。。
もしもっとシンプルな方法を知っている方がいましたらコメントお願いします。

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?