通过属性在数组中搜索对象的有效方法 [英] efficient way to search object in an array by a property
本文介绍了通过属性在数组中搜索对象的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,有类似的东西:
$array[0]->id = 'one';
$array[0]->color = 'white';
$array[1]->id = 'two';
$array[1]->color = 'red';
$array[2]->id = 'three';
$array[2]->color = 'blue';
实现类似方法的最快、最有效的方法是什么
what would be the fastest, most efficient way to implement a method like
函数 findObjectById($id){}
function findObjectById($id){}
如果我调用它会返回对象 $array[0]:
that would return the object $array[0] if i called:
$obj = findObjectById('one')
如果我将四"作为参数传递,则会返回 false.
and would return false if i passed 'four' as a param.
推荐答案
您可以迭代该对象:
function findObjectById($id){
$array = array( /* your array of objects */ );
foreach ( $array as $element ) {
if ( $id == $element->id ) {
return $element;
}
}
return false;
}
更快的方法是让数组的键等于对象的 id(如果唯一);
Faster way is to have an array with keys equals to objects' ids (if unique);
然后您可以按如下方式构建您的函数:
Then you can build your function as follow:
function findObjectById($id){
$array = array( /* your array of objects with ids as keys */ );
if ( isset( $array[$id] ) ) {
return $array[$id];
}
return false;
}
这篇关于通过属性在数组中搜索对象的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文