如果$gymnast
對象不在$gymnasts
數組中,我將它添加到我的表中。但是,當我將相同的對象添加到數組時,in_array()
失敗(返回1),並將重複的對象添加到數組中。使用print_r
,我看到$gymnast
對象顯然與$gymnasts
數組中的第一個元素相同,那麼爲什麼會發生這種情況?我該如何解決?in_array函數無法檢查具有多個屬性的對象
$體操運動員陣列
Array ([0] => Gymnast Object ([name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg) [1] => Gymnast Object ([name] => Shawn Johnson [age] => 25 [height] => 4' 11" [olympicYear] => 2008 [medalCount] => 4 [image] => shawn.jpg))
$體操運動員對象
Gymnast Object ([name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg)
的index.php
<?php
function isDuplicateEntry($gymnast, $gymnasts) {
foreach ($gymnasts as $gym) {
$gymArr = get_object_vars($gym);
$gymnastArr = get_object_vars($gymnast);
if (count(array_diff($gymnastArr, $gymArr)) == 0) { //gymnast object already exists in array
return true;
}
else {
return false;
}
}
}
//Add gymnast when press add submit button
if(isset($_POST['add'])){
//Set gymnast array to all gymnasts in data.txt
$gymnasts = read_file($filename);
//If form has valid elements & no duplicats, add to data.txt file
if($valid_name && $valid_age && $valid_feet && $valid_inches && $valid_olympicYear && $valid_medalCount && $valid_image){
$gymnast = get_gymnast_from_form();
//Make sure gymnast is not null
if(!is_null($gymnast)){
//Prevent from adding duplicates
if(!isDuplicateEntry($gymnast, $gymnasts)){
//Write task to file
write_file($filename, $gymnast);
//Add gymnast to global var gymnasts array
$gymnasts[] = $gymnast;
echo'<div class ="title">Gymnast Added!</div>';
}
}
}
?>
嗨。 in_array函數可能會比較使用那些引用而不是它的鍵和值的對象。嘗試實現一個函數來替換in_array。 –
看到這篇文章:http://stackoverflow.com/questions/17231925/php-in-array-object-comparing –