mzcoxfde mzcoxfde - 3 months ago 6
PHP Question

PHP: Display the same array value only once

I have a table called tags which contains the tag_name and the question_id. Just like Stack Overflow, I can insert each tags by exploding them with a comma. 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.

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.

Thanks in advance.

Answer

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:

select
    tag_name,
    count(tag_name) as tag_count
from
    tags
group by
    tag_name
order by
    count(tag_name) desc
Comments