やりたいこと。生息地が【丘陵】のポケモンを検索したい。
ただし生息地はカンマ区切りになっている
コード
<?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】です