简体   繁体   English

如何计算数组中的唯一值并存储在另一个数组 PHP 中?

[英]How to count unique values in array and store in another array PHP?

I am trying to gather together unique values in an array to be able to pass them to a new array so I can use the data to create a chart.我正在尝试将数组中的唯一值收集在一起,以便能够将它们传递给一个新数组,以便我可以使用这些数据来创建图表。

The data I have is as below:我的数据如下:

Array
(
    [0] => Array
        (
            [date] => 2020-09-17
            [device] => 2
            [time] => 15:51:37
            [rfid] => 23641
        )

    [1] => Array
        (
            [date] => 2020-09-17
            [device] => 2
            [time] => 15:52:20
            [rfid] => 5609
        )

    [2] => Array
        (
            [date] => 2020-09-17
            [device] => 2
            [time] => 15:53:23
            [rfid] => 5609
        )

    [3] => Array
        (
            [date] => 2020-09-17
            [device] => 2
            [time] => 16:02:44
            [rfid] => 5609
        )

)

What would I need to do to get an output such as the following:我需要做什么才能获得如下输出:


[date]=> 2020-09-17
[device]=>2
[RFID]=> 5609 [Count]=> 3
[RFID]=> 23641[Count]=> 1 

Or is this even possible?或者这甚至可能吗?

I changed the array from associative to an indexed array and then looped through to count the unique keys, and then add the count if the key had already been set.我将数组从关联数组更改为索引数组,然后循环计算唯一键,如果键已经设置,则添加计数。

$arrLength=count($count);

            $elementCount=array();

             for($i=0;$i<=$arrLength-1;$i++){
                $key=$count[$i];

            if(isset($elementCount[$key])){
                $elementCount[$key]++;

            } else {
                $elementCount[$key]=1;
            }
   }
   print_r($elementCount);
    echo'</pre>';   

Output as follows输出如下

Array
(
    [2020-09-17] => 4
    [15:51:37] => 1
    [2] => 4
    [23641] => 1
    [15:52:20] => 1
    [5609] => 3
    [15:53:23] => 1
    [16:02:44] => 1
)

This post helped :这篇文章帮助:

How to remove duplicate values from an array in PHP 如何从PHP中的数组中删除重复值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM