我正在尝试自动筛选我的在线银行对账单。这是我需要的一个简单示例。
我有一系列餐厅,我可以根据这些餐厅对信用卡账单进行排序:
$restaurants = array(
array("vendor" => "default",
"type" => "default"
),
array("vendor" => "dunkin",
"type" => "pastry"
),
array("vendor" => "mcdonald",
"type" => "fastfood"
),
array("vendor" => "olive",
"type" => "italian"
)
);
语句条目本身可以是一个相当具有描述性的字符串:
$string = "McDonald's Restaurants Incorporated";
我尝试过使用 array_search和 in_array ,但他们似乎做了与我需要的相反的事情,或者他们需要完全匹配,如下例所示,但这不是我需要的:
$result = array_search($string, array_column($restaurants, 'vendor'));
return $restaurants[$result]['type'];
// returns "default" because "McDonald's Restaurants Incorporated" != "mcdonald"
我希望能够将数组值“mcdonald”与包含该 block 的任何字符串相匹配,然后为其返回类型“fastfood”。不用担心处理多次出现的情况。
最佳答案
您需要组合一些东西 - a search-in-string method, and for it to be case insensitive .
您可以通过以下方式完成此操作:
/**
* 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;
}
像这样使用它:
$result = findRoughly("McDonald's", $restaurants);
关于php - 将 PHP 数组值与字符串的一部分进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690724/