合并数组并替换值

时间:2014-01-03 13:27:41

标签: php arrays

我有两个数组。 首先,我们称之为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)

第二,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)

我想合并这两个数组,但要使用第二个值,其中第一个id与第二个id相等。

预期结果将是:

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)

检查索引为0的状态。它从' Aktivan'(从array1)变为' Gubitan'就像我们在array2中一样。

怎么做?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以使用两个foreach循环轻松完成此操作:

foreach( $array1 as $key1=>$element1 ){
    foreach( $array2 as $element2 ){
        if ($element1['id'] == $element2['id'])
            {
              $array1[$key1]['status'] = $element2['status'];
            }
    }
}