Hello!

Tell me, please, in the direction of what to look for. task.

There is a multidimensional array of the form (it is possible to generate separate arrays, but their number can be different - probably, in multidimensional it will be easier to process):

Array ( [0] => Array ( [0] => Name 1 [1] => 1 [2] => 0 [3] => 7 ) [1] => Array ( [0] => Name 2 [1] => 1 [2] => 0 [3] => -10 ) [2] => Array ( [0] => Name 3 [1] => 0 [2] => 1 [3] => 6 ) [3] => Array ( [0] => Name 4 [1] => 0 [2] => 1 [3] => -11 ) [4] => Array ( [0] => Name 1 [1] => 1 [2] => 0 [3] => 10 ) [5] => Array ( [0] => Name 3 [1] => 0 [2] => 1 [3] => 7 ) ) 

It is required to combine arrays with identical keys [0]. Those. combine the names, with the values ​​of all the other keys added together.

The output should get the result, for example:

 [0] => Array ( [0] => Name 1 [1] => 2 [2] => 0 [3] => 17 ) [1] => Array ( [0] => Name 2 [1] => 1 [2] => 0 [3] => -10 ) ... 

An attempt was made to proceed from the solution: https://toster.ru/q/60856 - but then it is possible to create a new array, without copies of the names (i.e., the key [0] is combined), but the other keys cannot be combined.

What method to remove copies (connect by key [0]), so that the keys [1] [2] [3] from duplicates are combined - I find it difficult to understand.

    2 answers 2

    You can do the following:

     <?php $arr = array( array('Name 1', 1, 0, 7), array('Name 2', 1, 0, -10), array('Name 3', 0, 1, 6), array('Name 4', 0, 1, -11), array('Name 1', 1, 0, 10), array('Name 3', 0, 1, 7) ); $result = array(); foreach($arr as $block) { if(array_key_exists($block[0], $result)) { for($j = 1; $j < 4; $j++) { $result[$block[0]][$j] += $block[$j]; } } else { $result[$block[0]] = $block; } } echo '<pre>'; print_r($result); 

      For example, this solution is possible:

       <?php //Исходные данные из примера $array = array( array( 'Name 1', 1, 0, 7 ), array( 'Name 2', 1, 0, -10 ), array( 'Name 3', 0, 1, 6 ), array( 'Name 4', 0, 1, -11 ), array( 'Name 1', 1, 0, 10 ), array( 'Name 3', 0, 1, 7 ), ); $result = array(); foreach ($array as $arrayItem) { if (!isset($result[$arrayItem[0]])) { $result[$arrayItem[0]] = array( $arrayItem[0], $arrayItem[1], $arrayItem[2], $arrayItem[3] ); } else { $result[$arrayItem[0]][1] += $arrayItem[1]; $result[$arrayItem[0]][2] += $arrayItem[2]; $result[$arrayItem[0]][3] += $arrayItem[3]; } } $result = array_values($result); print_r($result); 

      The result is:

       Array ( [0] => Array ( [0] => Name 1 [1] => 2 [2] => 0 [3] => 17 ) [1] => Array ( [0] => Name 2 [1] => 1 [2] => 0 [3] => -10 ) [2] => Array ( [0] => Name 3 [1] => 0 [2] => 2 [3] => 13 ) [3] => Array ( [0] => Name 4 [1] => 0 [2] => 1 [3] => -11 ) ) 

      You don’t need to invent anything special here, just run through the source array and add unique entries to the resulting one. If there are matching names, then the values ​​of the remaining fields are added to the saved ones.