I
I
Igor Tkachenko2015-09-21 11:23:33
PHP
Igor Tkachenko, 2015-09-21 11:23:33

How to merge 2 arrays with the same values ​​(and add values)?

There is an array - pastebin.com/72cWnG8s
Tell me how the elements of the hour and day arrays, if they are repeated (exactly 2, if any of them does not come across, they do not need to be combined).
And with this 2 combined elements add up the sum of the intercations.
I tried crutches, but it doesn’t work out in any way, since the array 1.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Safonov, 2015-09-21
@foozzi

Please note that I changed the word intercations to interactions

/**
 *
 * Input array consists of elements as in example
 * <code>
 * ["1072645714669550333_2140738661"]=>
 *  array(3) {
 *  ["hour"]=>
 *  string(2) "23"
 *  ["day"]=>
 *  string(1) "6"
 *  ["interactions"]=>
 *  int(27)
 *}
 *["1071825259138202534_2140738661"]=>
 *  array(3) {
 *  ["hour"]=>
 *  string(2) "20"
 *  ["day"]=>
 *  string(1) "5"
 *  ["interactions"]=>
 *  int(46)
 *}
 * </code>
 * 
 * @param array $array
 *
 * @return array
 */
function addInteractions(array $array){

  $newArray = [];
  foreach($array as $k=>$subarray)//here $k is something like "1071156299686296080_2140738661"
  {
    if( !isset( $newArray[ $subarray['day'] ][ $subarray['hour'] ][ 'interactions' ]) ){
      $newArray[ $subarray['day'] ][ $subarray['hour'] ][ 'interactions' ] = 0;
    }
    $newArray[ $subarray['day'] ][ $subarray['hour'] ][ 'interactions' ] += $subarray['interactions'];

  }
  return $newArray;
}

O
Optimus, 2015-09-21
Pyan @marrk2

$all = "";
$all .= $old_array[$i]['hour'];
$all .= $old_array[$i]['day'];
$new_array[] = $all;
$uniq_array = unique(new_array);

Then you can parse back if necessary ...
Do not work with multidimensional arrays, work with the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question