简体   繁体   English

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

[英]Merge 2 arrays to single array if any two keys of both array matches

I have two arrays: 1. first array: 我有两个数组: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. second array: 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)

ON these array if values of two keys 'student_id' and 'unixdate' matches I want new array with the id from array one and other from array 2. 在这些数组中,如果两个键'student_id'和'unixdate'的值匹配,我希望新数组的id来自数组1,而另一个来自数组2。
OR 要么
replace the 'attendance' value to first array if 'student_id' and 'unixdate' of both array are same. 如果两个数组的'student_id'和'unixdate'相同,则将'attendance'值替换为第一个数组。
EDIT 编辑
my result should be like this: 我的结果应该是这样的:

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)

How can i do this? 我怎样才能做到这一点?

did you try with 2 foreach? 你试过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;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM