PHP如何在多行数组中查找包含指定城市的数组索引
为什么
array_search()没起作用? 你忽略的核心点是:array_search()是在数组值中寻找完全匹配的内容,但你的数组值是用逗号拼接的多城市字符串(比如"New York,Los Angeles,Washington"),和你要查找的单个城市"Washington"并不完全相等,所以这个函数当然找不到匹配的索引啦。
两种高效解决方法
方法1:用array_filter()快速筛选(推荐)
这是最简洁的写法,通过闭包遍历数组,拆分每个值为城市列表后检查目标城市是否存在,最后提取符合条件的键名:
$targetCity = "Washington"; $array1 = [ 'Alpha' => "New York,Los Angeles,Washington", 'Beta' => "New York,Los Angeles,Honolulu", 'Gamma' => "New York,Los Angeles,Washington" ]; // 过滤出包含目标城市的数组项 $matchedItems = array_filter($array1, function($cityStr) use ($targetCity) { // 拆分字符串为城市数组,同时处理可能的空格(可选但推荐) $cities = array_map('trim', explode(',', $cityStr)); return in_array($targetCity, $cities); }); // 提取对应的索引(键名) $result = array_keys($matchedItems); // 如果你需要逗号分隔的字符串结果 echo implode(',', $result); // 输出 "Alpha,Gamma"
方法2:精简版foreach遍历
如果你觉得闭包不够直观,也可以用更直白的foreach循环,比你之前尝试的写法更简洁高效:
$targetCity = "Washington"; $array1 = [ 'Alpha' => "New York,Los Angeles,Washington", 'Beta' => "New York,Los Angeles,Honolulu", 'Gamma' => "New York,Los Angeles,Washington" ]; $result = []; foreach ($array1 as $key => $cityStr) { $cities = array_map('trim', explode(',', $cityStr)); if (in_array($targetCity, $cities)) { $result[] = $key; } } echo implode(',', $result); // 同样输出 "Alpha,Gamma"
小提示
如果你的城市字符串里可能存在前后空格(比如" New York, Los Angeles "),一定要加上array_map('trim', ...)来去除每个城市的空格,避免因为格式问题导致匹配失败。
内容的提问来源于stack exchange,提问作者Aquaholic
相关产品推荐
相关产品推荐

