I have two multi dimensional arrays. I want to compare them and add unique items to a new array. I would like to compare each field of the array (year, month, day, time)
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"
}
}
Insert Array =
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"
}
}
In this case the first item from the insert array would be saved to the new array. I would like to do this with 100+ items potentially. The end goal is to not allow duplicate inserts on the table. Thanks for the input.
Found it: Compare two multidimensional arrays then create array of only unique
<?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;
?>
By changing the value in input array you can see how this function works