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 に答える
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 に答える