PHP:在数组中搜索对象


PHP: Search objects in an array

假设我有一个对象数组。

<?php
$people = array();
$people[] = new person('Walter Cook');
$people[] = new person('Amy Green');
$people[] = new person('Irene Smith');

如何在此数组中的对象中搜索某个实例变量?例如,假设我想搜索名为"Walter Cook"的 person 对象。

提前感谢!

这取决于

person类的构造,但如果它有一个保留给定名称的字段name,你可以通过这样的循环来获取这个对象:

for($i = 0; $i < count($people); $i++) {
    if($people[$i]->name == $search_name) {
        $person = $people[$i];
        break;
    }
}

这里是:

$requiredPerson = null;
for($i=0;$i<sizeof($people);$i++)
{
   if($people[$i]->name == "Walter Cook")
    {
        $requiredPerson = $people[$i];
        break;
    }
}
if($requiredPerson == null)
{
    //no person found with required property
}else{
    //person found :)
}
?>

假设nameperson类的公共属性:

<?php
// build the array of objects
$people = array();
$people[] = new person('Walter Cook');
$people[] = new person('Amy Green');
$people[] = new person('Irene Smith');
// search name
$searchName = 'Walter Cook';
// ascertain the presence of the name in the array of objects
$isMatch = false;
foreach ($people as $person) {
    if ($person->name === $searchName) {
        $isMatch = true;
        break;
    }
}
// alternatively, if you want to return all matches into 
// a new array of $results you can use array_filter
$result = array_filter($people, function($person) use ($searchName) {
    return $person->name === $searchName;
});

希望这对:)有所帮助

你可以在你的类中尝试这个

    //the search function
function search_array($array, $attr_name, $attr_value) {
    foreach ($array as $element) {
        if ($element -> $attr_name == $attr_value) {
            return TRUE;
        }
    }
    return FALSE;
}
//this function will test the output of the search_array function
function test_Search_array() {
    $person1 = new stdClass();
    $person1 -> name = 'John';
    $person1 -> age = 21;
    $person2 = new stdClass();
    $person2 -> name = 'Smith';
    $person2 -> age = 22;
    $test = array($person1, $person2);
    //upper/lower case should be the same
    $result = $this -> search_array($test, 'name', 'John');
    echo json_encode($result);
}