PHP:仅显示一次相同的数组值

时间:2016-08-12 17:38:56

标签: php arrays mysqli

我有一个名为tags的表,其中包含tag_name和question_id。就像Stack Overflow一样,我可以通过用逗号爆炸来插入每个标签。这很有效。

但我也想展示所有标签。假设这是我从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
    )

)

当我遍历它们时,我得到了

tag-1
tag-1
tag-2

但这不是我想要的。我在考虑像

这样的东西
tag-1 × 2
tag-2

我怎样才能实现这一目标? 我正在使用CodeIgniter,但这并不重要,因为我只想了解它的逻辑。

提前致谢。

2 个答案:

答案 0 :(得分:1)

我没有对此进行过测试,但这样的事情应该有效:

<?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>';
}

输出:

tag-1 × 2
tag-2

或者您可以在SQL中执行此操作:

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

答案 1 :(得分:1)

我对这个问题的回答:

$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