php只获取数组中第一次出现的单词
我有一组从数据库中提取的标签,我正在将标签导出到标签云中。我坚持只获取该词的第一个实例。例如:
$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);
}
}
}
I have an array of tags that I'm pulling from a database, I am exporting the tags out into a tag cloud. I'm stuck on getting only the first instance of the word. For example:
$string = "test,test,tag,tag2,tag3";
$getTags = explode("," , $string);
foreach ($getTags as $tag ){
echo($tag);
}
This would output the test tag twice. at first i thought i could use stristr
to do something like:
foreach ($getTags as $tag ){
$tag= stristr($tag , $tag);
echo($tag);
}
This is obviously silly logic and doesn't work, stristr
seems to only replace the first occurrence so something like "test 123" would only get rid of the "test" and would return "123" I've seen this can also be done with regex but I haven't found a dynamic exmaple of that.
Thanks,
Brooke
Edit: unique_array()
works if I'm using a static string but won't work with the data from the database because I'm using a while loop to get each rows data.
$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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用array_unique()
use
array_unique()
将您的单词用作字典的键,而不是值。
当你在做的时候,你也可以数一下它们!
Use your words as keys to the dictionary, not as values.
While you are at it, you can also count them!
我假设表中的每一行都包含多个标记,以逗号分隔,如下所示:
如果是这种情况,请尝试以下操作:
我会指出这效率不高。
另一种选择(已经在这里提到)是使用标签作为数组键,其优点是能够轻松地对它们进行计数。
你可以这样做:
I'm assuming that each row in your table contains more than one tag, separated by coma, like this:
If that's the case, try this:
I'd point out that this is not efficient.
Another option (already mentioned here) would be to use the tags as array keys, with the advantage of being able to count them easily.
You could do it like this:
我相信 php 的 array_unique 就是您正在寻找的:
http://php.net /manual/en/function.array-unique.php
I believe php's array_unique is what you are looking for:
http://php.net/manual/en/function.array-unique.php
在迭代数组之前使用 array_unique 函数?它删除每个重复的字符串并返回唯一的函数。
Use the array_unique function before iterating over the array? It removes every duplicate string and return the unique functions.