我的数组如下:
:contains(X AND Y)
:contains(X(any number of characters)Y)
我想计算每个ID,数组中存在特定ID的次数,并得到如下结果: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
)
);
,String2 count 3
等等......
问题是id可以是任何东西,行是通过其他键从数据库中获取的。
我已经尝试了,但我得到的只是空键和数组中项目的总数:
String3 count 2
答案 0 :(得分:0)
试试这个:
<?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
)
答案 1 :(得分:0)
$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']);
}
}
所以你在一个数组中有计数和str
你也可以直接从数据库
获取select str, count(id) from table_name group by id
答案 2 :(得分:0)
简单地这样做:让您的数组名称为$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
)
答案 3 :(得分:0)
使用array_column
和array_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
)
答案 4 :(得分:0)
由DB
制作GridView1.AddNewRow()