如果两个数组的任何两个键匹配,则将2个数组合并为单个数组

时间:2011-11-29 10:39:58

标签: php arrays

我有两个数组: 1.第一阵列:

array
  0 => 
    array
      'id' => int 1
      'section_id' => int 2
      'class_id' => int 25
      'student_id' => int 1
      'unixdate' => int 1322553600
      'date' => string '2011-11-29' (length=10)
      'attendance' => string 'present' (length=7)
  1 => 
    array
      'id' => int 2
      'section_id' => int 2
      'class_id' => int 25
      'student_id' => int 2
      'unixdate' => int 1322553600
      'date' => string '2011-11-29' (length=10)
      'attendance' => string 'absent' (length=6)

2。第二个数组:

array
  0 => 
    array
      'section_id' => int 2
      'class_id' => int 25
      'student_id' => int 1
      'unixdate' => int 1322553600
      'date' => string '2011-11-29' (length=10)
      'attendance' => string 'absent' (length=7)
  1 => 
    array
      'section_id' => int 2
      'class_id' => int 25
      'student_id' => int 3
      'unixdate' => int 1322553600
      'date' => string '2011-11-29' (length=10)
      'attendance' => string 'absent' (length=6)

在这些数组中,如果两个键'student_id'和'unixdate'的值匹配,我希望新数组的id来自数组1,而另一个来自数组2。
OR
如果两个数组的'student_id'和'unixdate'相同,则将'attendance'值替换为第一个数组。
修改
我的结果应该是这样的:

array
      0 => 
        array
          'id'  => int 1
          'section_id' => int 2
          'class_id' => int 25
          'student_id' => int 1
          'unixdate' => int 1322553600
          'date' => string '2011-11-29' (length=10)
          'attendance' => string 'absent' (length=7)

我该怎么做?

1 个答案:

答案 0 :(得分:2)

你试过2个foreach吗?

$result = array();
foreach($array1 as $data1)
{
  foreach($array2 as $data2)
  {
    if($data1['student_id'] == $data2['student_id'] and
       $data1['unixdate'] == $data2['unixdate'])
    {
        $tmp = array("id" => $data1['id']);
        $tmp = array_merge($tmp, $data2);

        $result[] = $tmp;
        break;
    }
  }
}