phparrays

Replace row data in a 2d array if identifying column matches new row data


I have two arrays. First, let's call it array1:

array (size=8)
  0 => 
    array (size=6)
      'id' => string '2' (length=1)
      'domacin' => string 'Man City' (length=8)
      'gost' => string 'Liverpool' (length=9)
      'tip' => string '1' (length=1)
      'kvota' => string '1.8' (length=3)
      'status' => string 'Aktivan' (length=7)
  1 => 
    array (size=6)
      'id' => string '4' (length=1)
      'domacin' => string 'Inter' (length=5)
      'gost' => string 'Milan' (length=5)
      'tip' => string '1' (length=1)
      'kvota' => string '2.5' (length=3)
      'status' => string 'Aktivan' (length=7)

And second, array2:

  'id' => string '2' (length=1)
  'domacin' => string 'Man City' (length=8)
  'gost' => string 'Liverpool' (length=9)
  'tip' => string '1' (length=1)
  'kvota' => string '1.8' (length=3)
  'status' => string 'Gubitan' (length=7)

I want to merge this two arrays but to use values from second where id from first is equal with id from second.

Expected result would be:

array (size=8)
  0 => 
    array (size=6)
      'id' => string '2' (length=1)
      'domacin' => string 'Man City' (length=8)
      'gost' => string 'Liverpool' (length=9)
      'tip' => string '1' (length=1)
      'kvota' => string '1.8' (length=3)
      'status' => string 'Gubitan' (length=7)
  1 => 
    array (size=6)
      'id' => string '4' (length=1)
      'domacin' => string 'Inter' (length=5)
      'gost' => string 'Milan' (length=5)
      'tip' => string '1' (length=1)
      'kvota' => string '2.5' (length=3)
      'status' => string 'Aktivan' (length=7)

Check the status where index is 0. It changed from 'Aktivan'(from array1) to 'Gubitan' like we had in array2.

How to do that?


Solution

  • foreach ($firstArr as &$item) {
        if ($item['id'] == $secondArr['id']) {
            $item = $secondArr;
        }
    }