-3

I have two arrays that I want to merge. I created the first one through a for() loop so that it includes the last seven days (only three here to keep it short):

array(7) {
  [0]=>
  array(2) {
    ["created_at"]=>
    string(10) "2017-08-15"
    ["errorCount"]=>
    string(1) "0"
  }
  [1]=>
  array(2) {
    ["created_at"]=>
    string(10) "2017-08-16"
    ["errorCount"]=>
    string(1) "0"
  }
  [2]=>
  array(2) {
    ["created_at"]=>
    string(10) "2017-08-17"
    ["errorCount"]=>
    string(1) "0"
  }
}

The other array includes data from a DB:

array(2) {
  [0]=>
  array(2) {
    ["created_at"]=>
    string(10) "2017-08-15"
    ["errorCount"]=>
    string(1) "4"
  }
  [1]=>
  array(2) {
    ["created_at"]=>
    string(10) "2017-08-16"
    ["errorCount"]=>
    string(1) "12"
  }
}

I want to merge these two together so that errorCount in the first array is overwritten whenever created_at is identical. I tried it with array_merge() directly but it only adds the rows of the second array to the end of the first one.

Any suggestions on how to solve this? Or is there a different way to approach it?

Magnar
  • 3
  • 2
  • 1
    Hint: `array('2017-08-15' => 4, ...)`. With an alternative array structure the answer becomes trivially obvious… – deceze Aug 28 '17 at 09:53

1 Answers1

0

Filter result by following statement:

$finArray = array_values(array_combine(array_map(function ($value) { 
   return $value['created_at']; 
}, $mergedArray), $mergedArray));
Mayank Vadiya
  • 1,437
  • 2
  • 19
  • 32