如何在php中合并两个没有重复值的数组?

时间:2011-11-28 05:58:59

标签: php arrays

我有两个数组: 1.这里的每个对象都是从数据库中恢复的一行。

    array
      1 => 
        object(stdClass)[41]
          public 'id' => string '1' (length=1)
          public 'class_id' => string '25' (length=2)
          public 'section_id' => string '2' (length=1)
          public 'student_id' => string '1' (length=1)
          public 'date' => string '2011-11-27' (length=10)
          public 'attendance' => string 'present' (length=7)
2 => 
        object(stdClass)[41]
          public 'id' => string '1' (length=1)
          public 'class_id' => string '25' (length=2)
          public 'section_id' => string '2' (length=1)
          public 'student_id' => string '3' (length=1)
          public 'date' => string '2011-11-27' (length=10)
          public 'attendance' => string 'present' (length=7)

2。另一个数组来自我的表单,看起来像这样。

array
  0 => 
    array
      'class_id' => string '25' (length=2)
      'section_id' => string '2' (length=1)
      'student_id' => int 1
      'date' => string '2011-11-27 00:00:00' (length=19)
      'attendance' => string 'present' (length=7)
  1 => 
    array
      'class_id' => string '25' (length=2)
      'section_id' => string '2' (length=1)
      'student_id' => int 2
      'date' => string '2011-11-27 00:00:00' (length=19)
      'attendance' => string 'present' (length=7)

我想做的是:
- 比较这两个并检查关键student_id和日期是否已经在数据库中 - 从表格数据的第二个数组中删除重复数据并插入数据 最终结果应该是:

array
  0 => 
    array
      'class_id' => string '25' (length=2)
      'section_id' => string '2' (length=1)
      'student_id' => int 2
      'date' => string '2011-11-27 00:00:00' (length=19)
      'attendance' => string 'present' (length=7)

3 个答案:

答案 0 :(得分:26)

尝试:

$c = [array_merge][1]($a,$b);

var_dump([array_unique][1]($c));

希望有所帮助

答案 1 :(得分:5)

通过将标志SORT REGULAR设置为参数来补充DemoUser的anwer已解决了我的“转换数组到字符串”问题:

$c = array_merge($a,$b);

$d = array_unique($c, SORT_REGULAR);

var_dump($d);

答案 2 :(得分:1)

由于您的数组(数据库和表单)都 NOT 完全相同,因此无法调用array_merge或array_unique函数。您将需要迭代数据库行一次,并将返回值存储在单独的基于键值的数组(Map)中。然后遍历表单返回的数组并搜索先前准备好的数组中的键,如果找到则从表单返回的数组中删除该元素。请考虑以下代码段:

// assuming database returned rows are in $rows array
// assuming form returned records are in $forms array

$dbArray = array();
foreach($rows as $r) {
   // need to convert string to int and string to date to match data in both sets
   $dbArray[ array( (int) $r->student_id, strtotime($r->date) ) ] = 1;
}

$diffArray = array();
foreach($forms as $f) {
   $key = array( $f['student_id'], strtotime($f['date']) );
   if (!array_key_exists($key, $dbArray))
      $diffArray[] = $f;
}

// now $diffArray will have the final result you're looking for