2017-02-27 102 views
0

如果$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>'; 
        } 
       } 
      } 
?> 
+0

嗨。 in_array函數可能會比較使用那些引用而不是它的鍵和值的對象。嘗試實現一個函數來替換in_array。 –

+0

看到這篇文章:http://stackoverflow.com/questions/17231925/php-in-array-object-comparing –

回答

0

不能使用in_array立即爲多維對象。你將不得不循環他們找出匹配。 使用array_intersect來檢查數組是否存在於另一個數組中。可以使用array_diff來匹配數組。

$flag = 0; 
foreach ($gymnasts as $gym) { 
    if (count(array_diff($gymnast, $gym)) == 0) { 
     echo 'It is present.'; 
     $flag = 1; 
     break; 
    } 
} 

if ($flag == 0) { 

    echo 'Not present'; 
} 

array_intersect

array_diff

ideone link array_intersect

ideone link array_diff

+0

我試過(見上面更新的代碼),但它沒有工作,即使'$ gymArr $'和'$ gymnastArr $'都是'Array([name] => Nastia Liukin [age] => 27 [height] => 5'3「[olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg)Array([name] => Nastia Liukin [age] => 27 [height] => 5'3「[olympicYear] => 2008 [medalCount] => 5 [image] => 。我是否有錯誤? – 14wml

+0

@ 15ongm你可以給你的代碼片段的鏈接。嘗試在我提供的ideone鏈接中輸入數據。 – Ayush

0

您可以使用array_filtercount

$is_in_array = count(array_filter($gymnasts, function($member) use ($gymnast) { 
    return $member == $gymnast; 
})) > 0; 
相關問題