douqiao3930 2014-02-26 15:40
浏览 109

计算多个PHP数组的出现次数[重复]

This question already has an answer here:

I'm looking for a way to count occurence on an array of array.

This is my array :

Array
(
[0] => Array
    (
        [id] => 671
        [title] => BIEND
        [img] => 
        [ville] => marseille
    )

[1] => Array
    (
        [id] => 670
        [title] => BIENC
        [img] => 
        [ville] => avignon
    )

[2] => Array
    (
        [id] => 669
        [title] => BIENB
        [img] => 
        [ville] => avignon
    )

)

And what I would like to have :

Array
(
[avignon] => 2
[marseille] => 1
)

I tried with array_count_values, but it dont seems to be the good way.

Any idea?

</div>
  • 写回答

4条回答 默认 最新

  • dtewnsdf47253 2014-02-26 15:44
    关注

    You could just go through it manually:

    $result = array();
    foreach($input as $item) 
    {
      $result[$item['ville']]++;
    }
    

    or, slightly nicer perhaps,

    $result = array();
    foreach($input as $item) 
    { 
      $city = $item['ville'];
      if(!array_key_exists($city, $result)) {
        $result[$city] = 1;
      } else {
        $result[$city]++;
      }
    }
    

    Alternatively, you could do some array_map magic to first get an array with all the cities, and then use array_count_values as you planned:

    $cities = array_count_values( array_map( function($a) { return $a['ville']; } ) );
    

    Note, I haven't tested this last solution, I personally think the first one expresses the intention better. If you would like to use this one because it is shorter (i.e. less readable) I'll leave it to you to debug and comment it

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作