php只获取数组中第一次出现的单词
-
05-07-2019 - |
题
我有一组从数据库中提取的标签,我正在将标签导出到标签云中。我坚持只获取该词的第一个实例。例如:
$string = "test,test,tag,tag2,tag3";
$getTags = explode("," , $string);
foreach ($getTags as $tag ){
echo($tag);
}
这将输出测试标签两次。起初我以为我可以使用 stristr
做类似的事情:
foreach ($getTags as $tag ){
$tag= stristr($tag , $tag);
echo($tag);
}
这显然是愚蠢的逻辑并且行不通 stristr
似乎只替换第一次出现,所以像“test 123”这样的东西只会删除“test”并返回“123”我已经看到这也可以用正则表达式来完成,但我还没有找到动态的例子那。
谢谢,
布鲁克
编辑: unique_array()
如果我使用静态字符串,则可以工作,但不能使用数据库中的数据,因为我使用 while 循环来获取每行数据。
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
if ($getTag_data)
{
while ($rowTags = mysql_fetch_assoc($getTag_data))
{
$getTags = array_unique(explode("," , $rowTags['tags']));
foreach ($getTags as $tag ){
echo ($tag);
}
}
}
解决方案
我假设表中的每一行都包含多个标签,用逗号分隔,如下所示:
Row0: php, regex, stackoverflow
Row1: php, variables, scope
Row2: c#, regex
如果是这种情况,请尝试以下操作:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
//fetch all the tags you found and place it into an array (with duplicated entries)
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
array_merge($getTags, explode("," , $row['tags']);
}
}
//clean up duplicity
$getTags = array_unique($getTags);
//display
foreach ($getTags as $tag ) {
echo ($tag);
}
我要指出的是,这效率不高。
另一种选择(已经在这里提到)是使用标签作为数组键,其优点是能够轻松地对它们进行计数。
你可以这样做:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
$tags = explode("," , $row['tags']);
foreach($tags as $t) {
$getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
}
}
}
//display
foreach ($getTags as $tag => $count) {
echo "$tag ($count times)";
}
- 请记住,这些代码都没有经过测试,只是为了让您了解一下。
其他提示
使用 array_unique()
$string = "test,test,tag,tag2,tag3";
$getTags = array_unique(explode("," , $string));
foreach ($getTags as $tag ){
echo($tag);
}
将您的单词用作词典的键,而不是值。
$allWords=array()
foreach(explode("," , $string) as $word)
$allWords[$word]=true;
//now you can extract these keys to a regular array if you want to
$allWords=array_keys($allWords);
当你在这里时,你也可以数数吧!
$wordCounters=array()
foreach(explode("," , $string) as $word)
{
if (array_key_exists($word,$wordCounters))
$wordCounters[$word]++;
else
$wordCounters=1;
}
//word list:
$wordList=array_keys($wordCounters);
//counter for some word:
echo $wordCounters['test'];
我相信php的array_unique就是你要找的东西:
在迭代数组之前使用 array_unique 函数?它删除每个重复的字符串并返回唯一的函数。
不隶属于 StackOverflow