Salman Raza
Salman Raza

Reputation: 350

Merge two associative array and delete the duplicate one

I have two associative key value pair of array. I want to merge it into one such that they key remains and the value which have "on_time" in the first array should neglect the value of that key in second array.

Here is my two arrays below

[att] => Array
        (
            [841] => on_time
            [842] => not_time
            [843] => not_time
        )

    [entatt] => Array
        (
            [841] => unexcused
            [842] => unexcused
            [843] => late
        )

Expected output what I am looking for is

[entatt] => Array
    (
        [841] => on_time
        [842] => unexcused
        [843] => late
    )

Any help ?

Upvotes: 0

Views: 68

Answers (2)

didierc
didierc

Reputation: 14750

You're looking for a way to walk both arrays in one go, and apply a function selecting the correct entry in case of collision. I don't think there's a builtin function for that.

function merge2($att, $entatt, $collision){
   $res = $att;
   foreach ($entatt as $key => $value) {
     if (isset($res[$key]))
       $res[$key] = $collision($res[$key],$value);
     else
       $res[$key] = $value;
   }
   return $res;
}

You should then be able to use it as follow:

merge2($att,$entatt,function($v1,$v2){
   return $v1 !== 'on_time' ? $v2 : $v1;
});

It should properly handle cases when $entatt or $att contain keys not in the other array (although it wasn't clear in your question if this was necessary).

Upvotes: 0

WizKid
WizKid

Reputation: 4908

This should work:

$result = array();
foreach ($att as $key => $value) {
    $result[$key] = $value !== 'on_time' ? $entatt[$key] : 'on_time';
}

Upvotes: 1

Related Questions