[英]PHP: Display the same array value only once
I have a table called tags which contains the tag_name and the question_id. 我有一个称为标签的表,其中包含tag_name和question_id。 Just like Stack Overflow, I can insert each tags by exploding them with a comma.
就像Stack Overflow一样,我可以通过用逗号将每个标签展开来插入它们。 That works.
这样可行。
But I also wanted to show all the tags. 但我也想显示所有标签。 Let's say this is the result I get after selecting it from the
tags
table. 假设这是我从
tags
表中选择结果后得到的结果。
Array (
[0] => Array (
[tag_name] => tag-1,
[question_id] => 1
)
[1] => Array (
[tag_name] => tag-1,
[question_id] => 2
)
[2] => Array (
[tag_name] => tag-2,
[question_id] => 3
)
)
When I iterate through them, I get 当我遍历它们时,我得到
tag-1
tag-1
tag-2
But that's not how I wanted it. 但这不是我想要的。 I was thinking of something like
我在想类似的东西
tag-1 × 2
tag-2
How can I achieve that? 我该如何实现? I'm using CodeIgniter but it doesn't really matter, because I only want to understand the logic of it.
我正在使用CodeIgniter,但这并不重要,因为我只想了解它的逻辑。
Thanks in advance. 提前致谢。
I haven't tested this but something like this should work: 我还没有测试过,但是类似的东西应该可以工作:
<?php
$tag_array = [
0 => [
'tag_name' => 'tag-1',
'question_id' => 1
],
1 => [
'tag_name' => 'tag-1',
'question_id' => 2
],
2 => [
'tag_name' => 'tag-2',
'question_id' => 3
],
];
$count_tags = array();
foreach($tag_array as $v)
{
if(!isset($count_tags[$v['tag_name']]))
{
$count_tags[$v['tag_name']] = 0;
}
++$count_tags[$v['tag_name']];
}
// Sort your tags from hi to low
arsort($count_tags);
foreach($count_tags as $k=>$v)
{
echo $k.($v > 1 ? ' x '.$v : '').'<br>';
}
Outputs: 输出:
tag-1 × 2 tag-2
Or you can just do this in SQL: 或者您可以在SQL中执行以下操作:
select
tag_name,
count(tag_name) as tag_count
from
tags
group by
tag_name
order by
count(tag_name) desc
My answer to the problem: 我对这个问题的回答:
$array = [
0 => [
'tag_name' => 'tag-1',
'question_id' => 1
],
1 => [
'tag_name' => 'tag-1',
'question_id' => 2
],
2 => [
'tag_name' => 'tag-2',
'question_id' => 3
],
];
$count = [];
foreach ($array as $arr)
{
if (empty($count[$arr['tag_name']]))
{
$count[$arr['tag_name']] = 1;
}
else
{
$count[$arr['tag_name']]++;
}
}
foreach ($count as $key => $c)
{
echo $key . (($c > 1) ? ' x' . $c : '') . '<br>';'
}
// outputs:
tag-1 x2
tag-2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.