共計(jì) 888 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 PHP 中,可以使用 array_search() 函數(shù)來(lái)搜索一個(gè)值在數(shù)組中的位置。對(duì)于對(duì)象數(shù)組,我們可以通過(guò)自定義一個(gè)回調(diào)函數(shù)來(lái)指定搜索條件。
下面是一個(gè)示例,演示如何將 array_search() 用于對(duì)象數(shù)組:
class Person {public $name;
public $age;
public function __construct($name, $age) {$this->name = $name;
$this->age = $age;
}
}
$person1 = new Person('Alice', 25);
$person2 = new Person('Bob', 30);
$person3 = new Person('Charlie', 35);
$people = [$person1, $person2, $person3];
// 自定義回調(diào)函數(shù),用于在對(duì)象數(shù)組中搜索特定的對(duì)象
function searchByName($person, $name) {return $person->name == $name;
}
// 在對(duì)象數(shù)組中搜索名字為 Bob 的對(duì)象
$index = array_search('Bob', array_column($people, 'name'));
if ($index !== false) {echo "Bob is found at index $index.";
} else {echo "Bob is not found in the array.";
}
在上面的示例中,我們首先定義了一個(gè) Person 類(lèi)來(lái)表示一個(gè)人的信息,然后創(chuàng)建了一個(gè)包含 Person 對(duì)象的數(shù)組 $people。接著,我們定義了一個(gè)自定義的回調(diào)函數(shù) searchByName(),用于根據(jù)名字在對(duì)象數(shù)組中進(jìn)行搜索。最后,我們使用 array_search() 函數(shù)和 array_column() 函數(shù)來(lái)搜索名字為 "Bob" 的對(duì)象,并返回其在數(shù)組中的索引位置。
通過(guò)這種方式,你可以輕松地使用 array_search() 函數(shù)在對(duì)象數(shù)組中搜索特定的對(duì)象。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完