计数未知键中的数组值


count array values from unknown key

我有一个类似的数组

Array ( [0] => Array ( 
            [id] => 48 
            [str] => String1 
        ) 
       [1] => Array ( 
           [id] => 48 
           [str] => String1 
       ) 
       [2] => Array ( 
           [id] => 49 
           [str] => String2 
       ) 
       [3] => Array ( 
           [id] => 49 
           [str] => String2 
       ) 
       [4] => Array ( 
           [id] => 47 
           [str] => String3 
       ) 
       [5] => Array ( 
           [id] => 47 
           [str] => String3 
       ) 
       [6] => Array ( 
           [id] => 49 
           [str] => String2 
       ) 
       [7] => Array ( 
           [id] => 48 
           [str] => String1 
       )
      );

我想得到每个ID的计数,特定ID在数组中存在的次数,并得到如下结果:String2 count 3String3 count 2等等…

问题是id可以是任何东西,行是通过其他键从数据库中提取的。

我试过了,但我得到的只是空密钥和数组中项目的总数:

$count = array();
      foreach($results as $r)
      {
        $key = array_keys($r->id);
        $count[$key]++;
      }
$count = array();
foreach($results as $r)
{
    if (isset($count[$r['id']]) {
        $count[$r['id']]['count']++;
    } else {
        $count[$r['id']] = array('count' => 1, 'string' => $r['str']);
    }
}

所以在一个数组中有count和str

你也可以直接从数据库中获取

select str, count(id) from table_name group by id

只需这样做:让您的数组名称为$array

$arr = array();
foreach($array as $val){
    if(isset($arr[$val['id']]))
        $arr[$val['id']] = $arr[$val['id']] + 1;
    else
        $arr[$val['id']] = 1;
}

结果

Array
(
    [48] => 3
    [49] => 3
    [47] => 2
)

使用array_columnarray_count_values函数的简单解决方案:

$arr = [
    ['id' => 48, 'str' => 'String1'],
    ['id' => 48, 'str' => 'String1'],
    ['id' => 49, 'str' => 'String2'],
    ['id' => 50, 'str' => 'String3'],
];
$ids = array_column($arr, 'id');
$counts = array_count_values($ids);
print_r($counts);

输出:

Array
(
    [48] => 2
    [49] => 1
    [50] => 1
)

http://php.net/manual/en/function.array-count-values.php

试试这个:

<?php 
$results = array(
    array("id" => '48','str' => "string1"),
    array("id" => '48','str' => "string1"),
    array("id" => '49','str' => "string1"),
    array("id" => '47','str' => "string1"),
    array("id" => '47','str' => "string1") 
    );
$count = array();
foreach($results as $r)
{
    @$count[$r['id']]++;  // it will add no of occurances of any id
}
print '<pre>';print_r($count);
exit;
?>

输出:

Array
(
    [48] => 2   // 48 id exist 2 times
    [49] => 1   // 49 id exist 1 times
    [47] => 2   // 47 id exist 2 times
)

通过DB 实现

select id, str, count(1) 
  from thetable 
   group by id