PHP循环并返回多维数组

时间:2018-02-14 13:29:13

标签: php arrays loops multidimensional-array foreach

我试图编写一个PHP函数来循环到一个多维数组中,以便将它与商业名称匹配,然后返回给我"业务类型"。

凭借我目前的技能,我编写了这个函数,但我想知道除了循环两次之外是否有更好的解决方案,因为我的真实数组比下面的例子大得多。

注意:我是学生,我已经搜索过StackOverflow,但无法找到我的需求。

function find_business_type($dealer_name) {
    $business_type = [
        "OEM"               => ["kia", "mercedes"],
        "Rent"              => ["rent", "rent-a-car"],
        "Workshop"          => ["shop", "workshop"],
        "Spare Parts"       => ["spare", "parts", "part"],
        "General Trading"   => ["gen", "general"]
    ];

    foreach ($business_type as $key => $values) {
        foreach ($values as $value) {
            if (strpos($dealer_name, $value) !== false) {
                return $key;
            }
        }
    }
}


$my_dealer = "super-stars-123 rent a car";
echo find_business_type($my_dealer);
  

输出:"租"

1 个答案:

答案 0 :(得分:3)

这是一个想法。实质上,您可以过滤数组并根据百分比获取与您的字符串匹配的所有行。请注意,array_filter将返回一个数组,其中包含所有匹配值,而不仅仅是一个匹配项。

    <?php

$dealer = "super-stars-123 rent a car";

$types = [
        "OEM"               => ["kia", "mercedes"],
        "Stars"             => ["super-stars", "123"],
        "Brown"             => ["super stars", "abc"],
        "Home"              => ["think rent", "123"],
        "Super"             => ["renter", "car"],
        "Rent"              => ["rent", "rent-a-car"],
        "Workshop"          => ["shop", "workshop"],
        "Spare Parts"       => ["spare", "parts", "part"],
        "General Trading"   => ["gen", "general"]
    ];

// Filter through your array
$results = array_filter($types, function($type) use ($dealer) {
    // explode your inner array to a string and then try to match it
    // to your search dealer text. This returns a % match.
    // I would play around with this algo logic below to get it to do what you want.
    return (similar_text($dealer, implode(", ",$type), $percent) >= 8);
});

var_dump($results);   

 array (size=4)
  'Stars' => 
    array (size=2)
      0 => string 'super-stars' (length=11)
      1 => string '123' (length=3)
  'Brown' => 
    array (size=2)
      0 => string 'super stars' (length=11)
      1 => string 'abc' (length=3)
  'Super' => 
    array (size=2)
      0 => string 'renter' (length=6)
      1 => string 'car' (length=3)
  'Rent' => 
    array (size=2)
      0 => string 'rent' (length=4)
      1 => string 'rent-a-car' (length=10)