0

I have a multidimensional array like so:

array(4) {
    [0] => array(2) {
        [0] => string(15)
        "One" 
        [1] => string(5)
        "11:31"
    }
  [1] => array(2) {
        [0] => string(4)
        "Two" 
        [1] => string(5)
        "11:31"
    }
  [2] => array(2) {
        [0] => string(15)
        "Three" 
        [1] => string(5)
        "11:31"
    }
  [3] => array(2) {
        [0] => string(4)
        "One" 
        [1] => string(5)
        "11:31"
    }
}

I am trying to get the ones with the first value removed but added up together. So it would end up like so:

array(3) {
    [0] => array(2) {
        [0] => string(15)
        "One" 
        [1] => string(5)
        "22:62"
    }
  [1] => array(2) {
        [0] => string(4)
        "Two" 
        [1] => string(5)
        "11:31"
    }
  [2] => array(2) {
        [0] => string(15)
        "Three" 
        [1] => string(5)
        "11:31"
    }
}

Note the last 'One' has been removed and the second value in the array has been added up there from two 11:31's to 22:62. I hope that makes sense.

Is there something or a specific function I should look at to push me in the right direction? Any help much appreciated.

This is not just a straight up removing duplicates from what I can tell, as none are ever exactly the same although the second values are in this example, they won't be in live data.

Skintest
  • 154
  • 3
  • 13

1 Answers1

0

You could make a loop and group elements into a new array using key [0]. It the key doesn't exists in the new array, simply add the new array. Otherwise, you could parse the existing value to add the new value:

$array = [
  ["One", "11:31"],
  ["Two", "11:31"],
  ["Three", "11:31"],
  ["One", "11:31"],
];

$out = [];
foreach ($array as $item) {
  // if $item[0] is not an existing key,
  if (!isset($out[$item[0]])) {
    // add $item as-is
    $out[$item[0]] = $item;
  } else {

    // parse current time
    list($h1, $m1) = explode(':', $item[1]);
    $m1 += $h1 * 60;

    // parse existing time
    list($h2, $m2) = explode(':', $out[$item[0]][1]);
    $m1 += $m2 + $h2 * 60;

    // compute new time
    $h = floor($m1 / 60);
    $out[$item[0]][1] = sprintf("%02d:%02d", $h, $m1-$h*60);
  }
}
// array_values removes 'named' keys. 
print_r(array_values($out));

Output (condensed):

Array
(
    [0] => Array ([0] => One [1] => 23:02)
    [1] => Array ([0] => Two [1] => 11:31)
    [2] => Array ([0] => Three [1] => 11:31)
)
Syscall
  • 19,327
  • 10
  • 37
  • 52