我正在尝试在codeigniter中从活动记录收到的结果中找到重复值的计数。
For example:
1 => 12
2 => 21
3 => 22
4 => 21
5 => 12
6 => 45
有没有办法可以找出总数,所以12 = 1,21 = 2,22 = 1,12 = 2,45 = 1等?
Codeigniter方式会很棒,但我也对PHP方式持开放态度。确定array_count_values不适用于以下数组:
Array
(
[0] => Array
(
[key_id] => 1790
[key_name] => printer brisbane
[link_id] => 1130
[link_url] => 99cards.com
)
[1] => Array
(
[key_id] => 1982
[key_name] => test
[link_id] => 1130
[link_url] => 99cards.com
)
)
有没有办法可以发现link_id计数是2?
我自己找到了答案。以下是代码:
$e = 0;
foreach ($q as $qs){
$i = 1;
foreach ($q as $qss){
if($qss['link_id'] == $qs['link_id']){
$q[$e]['link_count'] = $i;
}
$i++;
}
$e++;
}
答案 0 :(得分:3)
array_count_values()
为此目的而制作
它从输入中返回值的关联数组作为键,将计数作为值返回。
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
以上示例将输出:
Array (
[1] => 2
[hello] => 2
[world] => 1 )
答案 1 :(得分:0)
我们可以按如下方式手动完成:
$count_array = array();
foreach($results as $result)
{
$link_id = $result['link_id'];
if(isset($count_array[$link_id]))
{
$count_array[$link_id] = $count_array[$link_id]+1;
}
else
{
$count_array[$link_id] = 1;
}
}