PHP in_array对象比较? [英] PHP in_array object comparing?
本文介绍了PHP in_array对象比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
in_array
函数可以比较对象吗?
Can the in_array
function compare objects?
例如,我有一个对象数组,我想将它们分别添加到另一个数组中.是否可以像这样检查是否已添加对象:
For example, I have an array of objects and I want to add them distinctly to another array. Is it possible to check if an object has already been added like so:
in_array($distinct, $object);
还是还有其他方法?
推荐答案
The in_array function cannot compare objects.
您应该从对象中创建唯一的键/值对,并且在将新对象插入最终数组时只需要比较这些键即可.
You should create unique key-value pairs from your objects and only need to compare those keys when inserting a new object into your final array.
假设每个对象都有唯一的id
属性,可能的解决方案是:
Assuming that each object has an unique id
property, a possible solution would be:
$unique_objects = array();
// $data represents your object collection
foreach ($data as $item) {
if (!array_key_exists($item->id, $unique_objects)) {
$unique_objects[$item->id] = $obj;
}
}
这篇关于PHP in_array对象比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文