dongni8124 2012-12-03 16:54
浏览 52
已采纳

在数组中查找并获取每个字符串的计数

I am fetching some data from the db and then push them to an array. I need to find the count of some strings and print out the result (count) in an efficient way:

Array
(
    [0] => q1-1,q2-2,q3-2,q4-1,q5-2,q6-3,q7-1,q8-4,
    [1] => q1-1,q2-2,q3-1,q4-3,q5-3,q6-3,q7-2,q8-1,
    [2] => q1-1,q2-1,q3-1,q4-1,q5-1,q6-2,q7-2,q8-2,
    [3] => q1-3,q2-1,q3-1,q4-1,q5-2,q6-3,q7-1,q8-1,
    [4] => q1-2,q2-2,q3-3,q4-1,q5-3,q6-3,q7-1,q8-1,
    [5] => q1-1,q2-2,q3-3,q4-1,q5-2,q6-3,q7-1,q8-1,
    [6] => q1-3,q2-1,q3-1,q4-3,q5-2,q6-3,q7-2,q8-4,
    [7] => q1-2,q2-2,q3-3,q4-1,q5-2,q6-5,q7-1,q8-1,
    [8] => q1-1,q2-1,q3-2,q4-3,q5-3,q6-5,q7-1,q8-1,
    [9] => q1-2,q2-1,q3-1,q4-1,q5-3,q6-3,q7-1,q8-1,
    [10] => q1-3,q2-2,q3-3,q4-3,q5-4,q6-3,q7-1,q8-1,
    ...
)

Sample data is above.

I need to know how many occurences of q1-1, q1-2 ... q8-4 is in the array and print out readable version. Ex. The are 23: q1-1, 412: q1-2 and so on.

I was going to create an array of each string that needs to be searched that iterate through the array. For every result increment the resultVariable for that string but I'm not sure if that's the best way.

Suggestions?

  • 写回答

2条回答 默认 最新

  • douzao2992 2012-12-03 16:59
    关注

    Pretty simple, loop on your array, create sub arrays, and create a counter array:

    $counts = array () ;
    foreach ( $your_array as $row ) {
        $sub = explode(',', $row);
        foreach ( $sub as $subval ) {
            if ( array_key_exists ( $subval, $counts ) ) {
                $counts[$subval] ++ ;
            } else {
                $counts[$subval] = 1 ;
            }
        }
    }
    

    Here is $counts:

    Array (
        'q1-1' => 23,
        'q1-2' => 9,
        // and so on....
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化