douweinu8562 2015-07-29 03:26
浏览 106
已采纳

将PHP数组值与字符串的PART进行比较

I'm trying to automate sifting through my online bank statements. Here's a trivial example of what I need.

I have an array of restaurants against which I sort my credit card statements:

$restaurants = array(
    array("vendor" => "default",
            "type" => "default"
    ),
    array("vendor" => "dunkin",
            "type" => "pastry"
    ),
    array("vendor" => "mcdonald",
            "type" => "fastfood"
    ),
    array("vendor" => "olive",
            "type" => "italian"
    )
);

The statement entries themselves can be a rather descriptive string:

$string = "McDonald's Restaurants Incorporated";

I've tried using array_search and in_array, but they seem to do the reverse of what I need, or they need an exact match like in the example below, but it is not what I need:

$result = array_search($string, array_column($restaurants, 'vendor'));
return $restaurants[$result]['type'];

// returns "default" because "McDonald's Restaurants Incorporated" != "mcdonald"

I would like to be able to match the array value "mcdonald" to any string that contains that chunk of it, and then return type "fastfood" for it. Don't worry about handling multiple occurrences.

  • 写回答

4条回答 默认 最新

  • dtjw6660 2015-07-29 03:45
    关注

    You'll need a combination of things - a search-in-string method, and for it to be case insensitive.

    You can accomplish this with something like this:

    /**
     * Perform a string-in-string match case insensitively
     * @param  string $string
     * @param  array  $restaurants
     * @return string|false
     */
    function findRoughly($string, $restaurants)
    {
        $out = false;
        foreach ($restaurants as $restaurant) {
            // Set up the default value
            if ($restaurant['type'] == 'default' && !$out) {
                $out = $restaurant['type'];
                // Stop this repetition only
                continue;
            }
            // Look for a match
            if (stripos($string, $restaurant['vendor']) !== false) {
                $out = $restaurant['type'];
                // Match found, stop looking
                break;
            }
        }
        return $out;
    }
    

    And use it like so:

    $result = findRoughly("McDonald's", $restaurants);
    

    Example here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?