2016-05-04 1 views
0

Courseという名前のオブジェクト(適切な名前)Courseが配列内にあるかどうかを調べるために、in_array()を使用しています。PHP in_arrayでオブジェクトの比較を行う方法を変更する

1つの問題は、オブジェクト全体の比較ではなく、オブジェクトの比較を行うためにCourseオブジェクト内の特定のプロパティを使用することです。

具体的には、$course->getShortName()を使用して比較を行います。どうして?私のCourseオブジェクト内の他のすべてのプライベート変数は同じであることができるshort_nameプロパティを除いて異なる可能性があります。そのため、オブジェクトプロパティを実行するために使用したいのです。私Courseクラス

public function getShortName(){ 
    return $this->short_name; 
} 

tl;drから

public function overlap($courses, $course_temp) { 
    for ($i = 0; $i < count($courses); $i = $i + 1) { 
     if ($this->overlapCourses($courses[$i], $course_temp)) { 
      // Push the class that is conflicted to the conflictedClass 
      // array 
      // TODO: Figure out why it's being added to the list 
      if(!in_array($courses[$i], $this->conflictClasses)) { 
       array_push($this->conflictClasses, $courses[$i]); 
      } 

      // Push the class that is conflicted with to the 
      // conflictedClass array 
      // TODO: Figure out why it's being added to the list 
      if(!in_array($course_temp, $this->conflictClasses)) { 
       array_push($this->conflictClasses, $course_temp); 
      } 
      return false; 
     } 
    } 
    return false; 
} 

ゲッター:比較を行い

メソッドの代わりに、比較対象のオブジェクト

+0

in_arrayの動作を変更することはできませんが、おそらくこれは参考になります:http://php.net/manual/de/function.array-uintersect.php – colburton

答えて

1

の一つの特性を比較私は既存のfを見ることができませんここに適用される統制。 あなたが欲しいものを実行するためにarray_filter使用することができます。もちろん、

function object_in_array($needle, array $array, $method) { 
    $propertyToMatch = $needle->$method(); 
    // the $matches var will contain all the objects that have the property matching your object property 
    $matches = array_filter($array, function($object) use ($propertyToMatch, $method) { 
     return $propertyToMatch === $object->$method(); 
    }); 

    // If there is at least 1 result, your object property is matching one of your array of objects 
    return count($matches) > 0; 
} 

使用

if (object_in_array($myObject, $courses, 'getShortName')) { 
    .... 
} 

を使用すると、$メソッドメソッドが存在するかどうかを確認し、例外がない場合はをスローする必要があります。

+0

ありがとう! array_filterの大きな点は何ですか? – theGreenCabbage

+0

申し訳ありませんあなたの質問がわかりません – jiboulex