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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大