-1

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?

emstay
  • 21
  • 5
  • Yes, it is possible. – u_mulder Sep 26 '20 at 15:44
  • hint, grab all dates or device with array_column, make them unique with array_unique.. loop over them, use array search to pick out the items which match the date or device, either add a new item or append/update existing. what have you tried? – Lawrence Cherone Sep 26 '20 at 15:44
  • I had tried sizeof, and array_count but they would both just give me the count - not retaining the values of rfid – emstay Sep 26 '20 at 16:10

1 Answers1

0

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

emstay
  • 21
  • 5