【问题标题】:How to count the elements in array which are more than one (php)如何计算数组中超过一个的元素(php)
【发布时间】:2013-08-31 11:37:39
【问题描述】:

在 php 中,我有一个 ArrayList。让我们说

$list = {1000,7000,5000,1000,6000,5000,1000,2000};

所以我想做的是对列表中的每个元素进行计数:

如上例,

      1000 comes three times then count of 1000 = 3

      5000 comes two times then count of 5000 = 2,etc.

我想access that count of different elements separately

编辑:

这里有for循环

    for($i=0;$i<count($trip);$i++)
    {
        // Here list will be new everytime for loop run.
        $list = $Users->Matches($trip[$i]);
    }
    // ----------------------------------------------------------------------
    Here what I want to do is that "Take all the element of list for value of 
    $i : 0 to count($trip)" and "add it into another list lets say $allList 
    and access" as below :
    // -----------------------------------------------------------------------
    $cnt_arr = array_count_values($allList);

    foreach($cnt_arr as $key => $value) {
        echo "\n\n Count of ".$key." = ".$value." ";
    }

输出:

    Lets say for loop runs first time :
    $list = {1000,7000,5000}
    Now for loop second time :
    $list = {8000,1000,9000}

    Now for loop is completed and at the end I want the $allList value as below :
    $allList = {1000,7000,5000,8000,1000,9000}(which has all the elements of above-appended list)

那么我该怎么做呢?

请指导我。任何帮助将不胜感激。

【问题讨论】:

    标签: php arrays arraylist count


    【解决方案1】:

    试试array_count_values 喜欢

    $cnt_arr = array_count_values($list);
    
    foreach($cnt_arr as $key => $value) {
        echo "Count of ".$key." = ".$value."<br>";
    }
    

    看到这个LINK

    根据您的编辑,您需要像数组一样存储它们

    for($i=0;$i<count($trip);$i++)
    {
        // Here list will be new everytime for loop run.
        $temp_list = $Users->Matches($trip[$i]);
        foreach($temp_list as $tmp) {
            $list[] = $tmp;
        }
    }
    

    【讨论】:

    • 感谢您的回答。它适用于 array_count_values($list)。但是对于 echo "Count of ".$key." = ".$value."
      ";它是这样打印的 Count of 0 = 1000
    • 考虑我们需要$cnt_arr的foreach
    • 请查看我编辑的问题。我期待你的积极答复。我会接受你的回答。谢谢。
    • 好的,我看到了。你能告诉我你想要的输出数组吗?\
    • 在这种情况下,根据我的新编辑,您需要使用 list[]
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多