改变PHP in_array对象比较的方式

时间:2016-05-04 14:17:08

标签: php object

我正在使用in_array()检查一个名为Course的{​​{1}}对象是否在数组中。

我遇到的一个问题是,我想在我的Course对象中使用特定属性来进行对象比较,而不是比较整个对象。

具体来说,我想使用Course进行比较。为什么?因为$course->getShortName()对象中的所有其他私有变量可能不同,但Course属性可以保持不变,这就是我想用它来执行对象属性的原因。

进行比较的方法

short_name

来自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; } 课程

的获取者
Course

public function getShortName(){ return $this->short_name; } :比较对象的一个​​属性

,而不是比较对象

1 个答案:

答案 0 :(得分:1)

我看不到任何适用于此处的现有功能。 您可以使用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')) {
    ....
}

当然你应该验证$ method方法是否存在,如果没有则抛出异常。