Add PHP multidimensional array

Asked

Viewed 149 times

0

Good morning, I have the following array:

Array (  [0] => Array(  [data] => 2018-06-08
                        [grupo] => 1 
                        [maq] => 1
                        [segundos] => 10089 ) 
         [1] => Array ( [data] => 2018-06-08 
                        [grupo] => 1 
                        [maq] => 2 
                        [segundos] => 6300 ) 
        [2] => Array  ( [data] => 2018-06-08 
                        [grupo] => 1 
                        [maq] => 1 
                        [segundos] => 3600 ) 
        [3] => Array (  [data] => 2018-06-09
                        [grupo] => 1
                        [maq] => 1 
                        [segundos] => 3600 ) )

My question is the following, how can I add only the key[seconds], where the key [date] and [maq] were the same (repeat), as the following output:

 Array (  [0] => Array( [data] => 2018-06-08
                        [grupo] => 1 
                        [maq] => 1
                        [segundos] => 13689 ) 
         [1] => Array ( [data] => 2018-06-08 
                        [grupo] => 1 
                        [maq] => 2 
                        [segundos] => 6300 ) 
        [2] => Array (  [data] => 2018-06-09
                        [grupo] => 1
                        [maq] => 1 
                        [segundos] => 3600 ) )

1 answer

0

I got it with the following code:

$second_array = array_reduce($first_array, function($carry, $item) {
    $key = sprintf('%s-%s', $item['data'], $item['maq']);
    if (isset($carry[$key])) {
        $carry[$key]['segundos'] += $item['segundos'];
    } else {
        $carry[$key] = $item;
    }
    return $carry;
});


$second_array = array_values($second_array);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.