确定5个数组中是否存在字符串的最佳方法是什么?

时间:2013-09-26 10:22:47

标签: php

我有一个带有类别的标记,说:“行李”我想知道哪些父类别是行李在地图上设置特定标记。

我创建了一个我需要显示的每个类别的顶级类别列表。类似的东西:

$education = [ "adultedu", "collegecounseling", "collegeuniv", "educationservices", "elementaryschools", "highs|chools", "preschools", "privatetutors", "religiousschools", "specialed", "specialtyschools", "artschools", "cprclasses", "cookingschools", "cosmetology_schools"]

我有相同的运输,购物,健康等清单......

搜索关键字来自哪个类别的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

使用数组并在使用in_array时迭代:

$arrays = array(
    'education' => &$education,
    'transport' => &$transport,
    'shopping'  => &$shopping,
    'health'    => &$health
);

$searchingFor = 'foo';

$searchingForCategory = null;
foreach ($arrays as $category => $array) {
    if (in_array($searchingFor, $array)) {
        $searchingForCategory = $category;
        break;
    }
}

var_dump($searchingForCategory); //education / transport / shopping / health / NULL

答案 1 :(得分:0)

您必须使用in_array()函数检查每个数组。

 if (in_array('luggage', $education)) {
     // found
 }

此外,您可以将所有顶级类别添加到一个数组,让我们说$topCategories;) 然后你可以用简单的循环检查所有:

 $foundInCategory = '';
 foreach ($topCategories as $name => $subCategories) {
     if (in_array('luggage', $subCategories)) {
         $foundInCategory = $name;
         break;
     }
 }

它会将找到子类别的类别名称添加到变量$foundInCategory