计算数组中的键

时间:2015-01-07 19:47:51

标签: 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
    {
      $results[$row[$key]] = 1;
    }
  }

  return $results;
}

3 个答案:

答案 0 :(得分:1)

要通过搜索计算二维数组中的键,我会这样做 -

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');

EXAMPLE

array_keys() count()

答案 1 :(得分:0)

对于二维数组,请尝试:

$result = count(array_column($array, $key));
{p <1}}需要

PHP&gt; = 5.5.0或使用PHP Implementation of array_column()

答案 2 :(得分:-1)

只需使用count()函数,如:

count($array);

请参阅:http://php.net/manual/pt_BR/function.count.php

您也可以使用此函数计算数组变量。

希望它对你有所帮助。