【发布时间】:2017-08-07 15:13:58
【问题描述】:
我知道这似乎是一个疯狂的问题,但我无法找出以下情况的最佳解决方案。
我有一个“类别”数组,每个类别都有一个“搜索”字符串。这些搜索是一串逗号分隔的单词,用作strpos 以匹配类别。
类别数组示例
$categories = [
0 => [
'category' => 'Foo',
'searches' => 'fet,cre,oho'
],
1 => [
'category' => 'Bar',
'searches' => 'lois,vreb,mon'
],
]
这就是问题所在。假设我有 secret 这个词。如您所见,$categories 中的第一个数组有searches,其中包含字符串中的cre。我遇到的问题是根据给定字符串(在此示例中为“秘密”)提供类别的方法,该类别在搜索中以逗号分隔的单词之一中具有strpos(),然后返回类别(只能养一只猫)。
我正在寻找的结果:
function findCategory($string)
{
$category = false;
// code to take the string,
// look through $categories
// find the first occurrence of a string position
// in the comma separated list of possible matches
return $category ? $category : 'Other';
}
echo findCategory('secret'); // Foo
echo findCategory('monster'); // Bar
echo findCategory('cohort'); // Foo
echo findCategory('tense'); // Other
【问题讨论】:
-
您应该尝试自己编写代码。在doing more research 之后,如果您有问题发布您尝试过的方法,并清楚地解释什么不起作用,并提供a Minimal, Complete, and Verifiable example。阅读How to Ask 一个好问题。请务必take the tour 并阅读this。
-
问题有点笼统,你自己还没试过吗?
-
最好我能想到 id 循环遍历所有类别和每个类别中的搜索,然后将每个搜索视为正则表达式模式并将其与原始字符串匹配。如果有匹配项,请分配类别。
-
从你的问题来看,你有办法。你只需要为它编写代码。一旦您在尝试编写代码时遇到实际问题,请联系我们。