如何比较两个多维数组的唯一条目?

时间:2015-02-26 23:01:30

标签: php mysql arrays

我有两个多维数组。我想比较它们并将新项添加到新数组中。我想比较数组的每个字段(年,月,日,时间)

Current Array =

array(0) {
  [0]=>
  array(5) {
    ["year"]=>
    string(4) "2015"
    ["month"]=>
    string(1) "3"
    ["day"]=>
    string(1) "5"
    ["time"]=>
    string(4) "0900"
  }
 [1]=>
  array(5) {
    ["year"]=>
    string(4) "2015"
    ["month"]=>
    string(1) "3"
    ["day"]=>
    string(1) "6"
    ["time"]=>
    string(4) "0800"
  }
}

插入数组=

array(1) {
  [0]=>
  array(5) {
    ["year"]=>
    string(4) "2015"
    ["month"]=>
    string(1) "3"
    ["day"]=>
    string(1) "6"
    ["time"]=>
    string(4) "0800"
  }
  [1]=>
  array(5) {
    ["year"]=>
    string(4) "2015"
    ["month"]=>
    string(1) "3"
    ["day"]=>
    string(1) "7"
    ["time"]=>
    string(4) "0800"
  }
}

在这种情况下,插入数组中的第一项将保存到新数组中。我想这可能有100多个项目。最终目标是不允许在表上重复插入。感谢您的投入。

找到它: Compare two multidimensional arrays then create array of only unique

1 个答案:

答案 0 :(得分:0)

<?php
  function isMatch($input, $database){
         //check if there is a match
       $match = array_diff($input, $database);
        /**Just incase there is a match array_diff returns an empty array
       And when there is no match, it returns an array with keys and values
       Where by in this case will result into false.**/ 
       if($matches == array()):
           return true;
       else:
           return false;
       endif;

 }

  /***using the function
  Suppose this where to cime from the form 
 fetch from the form fields
 if(isset($_POST['send'])):
 $year = $_POST['year'];
 $month = $_POST['month'];
 $day   = $_POST['day'];
 $time = $_POST['time'];

 $input = array('year'  => $year,
              'month' => $month,
              'day'   => $day,
              'time'  => $time
 );
  **************************/


 $input = array('year'  => 2015,
           'month' => 2,
           'day'   => 28,
           'time'  => 2000
);

$database = array('year'  => 2015,
              'month' => 2,
              'day'   => 28,
              'time'  => 2000
);
if(!isMatch($input, $database)):
   echo "okay save the new data";
else:
   echo "Data already in database";
endif;          

?>

通过更改输入数组中的值,您可以看到此函数的工作原理

相关问题