Magnar Magnar - 2 months ago 18
PHP Question

Merge two arrays when string is identical

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?

Answer Source

Filter result by following statement:

$finArray = array_values(array_combine(array_map(function ($value) { 
   return $value['created_at']; 
}, $mergedArray), $mergedArray));