PHP:搜索数组中的对象

时间:2013-11-08 01:59:53

标签: php arrays object

假设我有一系列对象。

<?php

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

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

提前致谢!

4 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分: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 :)
}

?>

答案 2 :(得分: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;
});

希望这有助于:)

答案 3 :(得分: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);
}