Home > database >  How to get common date and sum of counts from an array variable in php
How to get common date and sum of counts from an array variable in php

Time:08-10

I am working with array in PHP. I would like to detect the presence of duplicate dates , then sum of count the number of duplicate values and out put the results. For example, given the following Array:

Array
(
    [0] => Array
        (
            [viewscount] => 18
            [date] => 2022-07-14
        )

    [1] => Array
        (
            [viewscount] => 19
            [date] => 2022-07-18
        )

    [2] => Array
        (
            [viewscount] => 1
            [date] => 2022-07-19
        )

    [3] => Array
        (
            [viewscount] => 1
            [date] => 2022-08-03
        )

    [4] => Array
        (
            [viewscount] => 1
            [date] => 2022-08-03
        )

)

I would like to print :

Array
(
    [0] => Array
        (
            [viewscount] => 18
            [date] => 2022-07-14
        )

    [1] => Array
        (
            [viewscount] => 19
            [date] => 2022-07-18
        )

    [2] => Array
        (
            [viewscount] => 1
            [date] => 2022-07-19
        )

    [3] => Array
        (
            [viewscount] => 2
            [date] => 2022-08-03
        )
)

CodePudding user response:

We build $indexed array so that it contains single record for every unique date in $data. We go throug $data record by record. If given date already exists in $indexed, we just inrease the count. Otherwise, we copy the record into $indexed.

$data = [
    ['viewscount' => 18, 'date' => '2022-07-14'],
    ['viewscount' => 19, 'date' => '2022-07-18'],
    ['viewscount' => 1, 'date' => '2022-07-19'],
    ['viewscount' => 1, 'date' => '2022-08-03'],
    ['viewscount' => 1, 'date' => '2022-08-03'],
];

// prepare empty result
$indexed = [];

// go through data record by record
foreach ($data as $record) {

    // get the date of current record into variable for easier manipulation
    $key = $record['date'];

    // if the date has been encountered previously, just add the amount
    if (array_key_exists($key, $indexed)) {

        $indexed[$key]['viewscount']  = $record['viewscount'];
    }
    // this is first time we encounter this date, create new row in resulting array
    else {

        $indexed[$key] = $record;
    }
}

// array_values() just removes the keys
print_r(array_values($indexed));

CodePudding user response:

$videos = [
  ['viewscount' => 18, 'date' => '2022-07-14'],
  ['viewscount' => 19, 'date' => '2022-07-14'],
  ['viewscount' => 1, 'date' => '2022-07-19'],
  ['viewscount' => 1, 'date' => '2022-07-19'],
  ['viewscount' => 1, 'date' => '2022-08-03'],
  ['viewscount' => 1, 'date' => '2022-08-03'],
];

for ($i = 0; $i < count($videos); $i  ) {
  for ($j = $i 1; $j < count($videos); $j  ) {
    if ($videos[$i]['date'] === $videos[$j]['date']) {
      $videos[$i]['viewscount']  = $videos[$j]['viewscount'];
      unset($videos[$j]);
      $videos = array_values($videos);
    }
  }
}

var_dump($videos);

results into

array(3) {
  [0]=>
  array(2) {
    ["viewscount"]=>
    int(37)
    ["date"]=>
    string(10) "2022-07-14"
  }
  [1]=>
  array(2) {
    ["viewscount"]=>
    int(2)
    ["date"]=>
    string(10) "2022-07-19"
  }
  [2]=>
  array(2) {
    ["viewscount"]=>
    int(2)
    ["date"]=>
    string(10) "2022-08-03"
  }
}

CodePudding user response:

We use array_reduce function to solve this problem. The initial value will be given to this function as third parameter which will be an empty array at start. Then we will fetch each date as key from current item. If our initial array contains that key, then we increment counts otherwise we create new item in our initial array.

// $carry is our index / our final array
$reduced_array = array_reduce($array, function ($carry, $item) {
    // Get key from current select item
    $key = $item["date"];
    // Search for that key in our $carry array
    if (array_key_exists($key, $carry)) {
        // key exists meaning we need to increment views of this key
        $carry[$key]["viewscount"]  = $item["viewscount"];
    } else {
        // key doesn't exist, we push current item to that key
        $carry[$key] = $item;
    }
    return $carry;
}, []);

echo "<pre>";
// array_values reindexes array with 0 based index and remove our dated indices
print_r(array_values($reduced_array));
echo "</pre>";

This can be achieved using loops but I prefer to use library functions available to use.

  •  Tags:  
  • php
  • Related