0

假设我有一个对象数组。

<?php

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

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

提前致谢!

4

4 回答 4

4

这取决于person类的构造,但如果它有一个name保留给定名称的字段,则可以使用如下循环获取此对象:

for($i = 0; $i < count($people); $i++) {
    if($people[$i]->name == $search_name) {
        $person = $people[$i];
        break;
    }
}
于 2013-11-08T02:11:13.523 回答
2

这是:

$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 :)
}

?>
于 2013-11-08T02:10:35.970 回答
1

假设这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;
});

希望这可以帮助 :)

于 2013-11-08T02:17:40.957 回答
0

好吧,你可以在课堂上试试这个

    //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);
}
于 2013-11-08T02:31:30.400 回答