Php 在数组中计数键
我已经编写了下面的函数,它接受一个二维数组并返回一个键出现的次数,但感觉我可能在这里重新发明轮子,有没有简单的方法Php 在数组中计数键,php,arrays,sum,Php,Arrays,Sum,我已经编写了下面的函数,它接受一个二维数组并返回一个键出现的次数,但感觉我可能在这里重新发明轮子,有没有简单的方法 function countKeys($array, $key) { $results = array(); foreach($array as $row) { if (array_key_exists($row[$key], $results)) { $results[$row[$key]] += 1; } else
function countKeys($array, $key)
{
$results = array();
foreach($array as $row)
{
if (array_key_exists($row[$key], $results))
{
$results[$row[$key]] += 1;
}
else
{
$results[$row[$key]] = 1;
}
}
return $results;
}
只需使用count()函数,如下所示:
count($array);
见:
您也可以使用此函数对变量数组进行计数
希望对您有所帮助。要通过搜索计算二维数组中的键,我会这样做-
function countKeys($array,$search){
$key_count = array(); // new array
foreach($array as $record) {
$keys = array_keys($record);
foreach($keys as $key){
if($key == $search){ // check against the search term
array_push($key_count, $key); // add the key to the new array
}
}
}
return count($key_count); // just count the new array
}
echo countKeys($records, 'last_name');
对于二维阵列,请尝试:
$result = count(array_column($array, $key));
PHP>=5.5.0需要
array\u column()
或使用OP states二维数组。我已经更新了答案。它稍微干净一点,可能对你有帮助。