0
0

【PHP】指定した値が配列のカンマ区切りに含まれてるか検索

Last updated at Posted at 2024-04-26

やりたいこと。生息地が【丘陵】のポケモンを検索したい。

ただし生息地はカンマ区切りになっている

コード

<?php
$query_data = [
    ['id'=> 1,'name'=>'イシツブテ','habitat'=>'渓谷,洞窟']
    ,['id'=> 2,'name'=>'イワーク','habitat'=>'砂漠,鉱山']
    ,['id'=> 3,'name'=>'ウソッキー','habitat'=>'鉱山,地中']
    ,['id'=> 4,'name'=>'ハガネール','habitat'=>'丘陵,窪地']
    ,['id'=> 5,'name'=>'サイドン','habitat'=>'渓谷,丘陵']
];


function searchValueInArray($query_data, $value) {
    $keys = [];
    foreach ($query_data as $key => $item) {
        $elements = explode(',', $item['habitat']);
        if (in_array($value, $elements)) {
            $keys[] = $key;
        }
    }
    return $keys;
}


// 検索したい値
$searchValue = "丘陵";

// 関数を呼び出す
$keys = searchValueInArray($query_data, $searchValue);

if (!empty($keys)) {
    echo "【{$searchValue}】が生息地のポケモンが見つかったよ。レコード番号は【" . implode(', ', $keys).'】です';
} else {
    echo "【{$searchValue}】が生息地のポケモンはいなかったよ";
}

結果

丘陵が生息地のポケモンが見つかったよレコード番号は3, 4です

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