比较PHP对象数组
我需要迭代两组数组,如果它们匹配或不匹配,则需要将它们设置为不同的样式 一个快速工作的例子是:比较PHP对象数组,php,arrays,object,Php,Arrays,Object,我需要迭代两组数组,如果它们匹配或不匹配,则需要将它们设置为不同的样式 一个快速工作的例子是: $animal1 = array('elephant', 'giraffe', 'lion'); $animal2 = array('elephant', 'giraffe', 'cow'); $animal3 = array('elephant', 'lion', 'giraffe'); foreach($animal1 as $animal) { echo $animal . " ";
$animal1 = array('elephant', 'giraffe', 'lion');
$animal2 = array('elephant', 'giraffe', 'cow');
$animal3 = array('elephant', 'lion', 'giraffe');
foreach($animal1 as $animal) {
echo $animal . " ";
if(in_array($animal, $animal2, true)) {
echo "yay<br />";
}
else {
echo "no<br />";
}
}
因此,在第一个示例中使用$example数组是行不通的。有人知道我该怎么做吗?显然,in_对象在PHP中不存在…您可以使用
(array)
类型转换轻松地将对象转换为数组。比如说,您有一个对象
$obj
Do
$arr=(数组)$obj代码>
就是这样,您有一个数组,其中的键与属性名完全相同。
其他一切都一样 如果要在数组中找到的对象中搜索值字符串,可以在数组中编写自己的
函数:
function in_array_of_objects($needle, $haystack, $objValue) {
foreach ($haystack as $obj) {
if ($needle === $obj->$objValue) return true;
}
return false;
}
然后:
如果要保留严格的功能,请执行以下操作:
function in_array_of_objects($needle, $haystack, $objValue, $strict = false) {
if ($strict) {
foreach ($haystack as $obj) {
if ($needle === $obj->$objValue) return true;
}
} else {
foreach ($haystack as $obj) {
if ($needle == $obj->$objValue) return true;
}
}
return false;
}
注意:我阻止了在foreach
循环中的if语句中添加$strict
检查,以减少处理时间,不管它有多小
但是,假设所有数组实际上都包含对象,并且将对象与对象进行比较
但是,它们必须仍然是同一类的实例。该函数检查数组中是否存在值,而不是对象
比较对象与比较值的方式不同。看看这个
说你应该修改你的代码
试试这个:
foreach ($arr as &$member) {
if ($member == $obj) {
return TRUE;
}
}
return FALSE;
或者这个:
foreach ($arr as &$member) {
if ($member === $obj) {
return TRUE;
}
}
return FALSE;
注意:您可以在“比较对象”链接中看到如何创建一个函数来比较对象一个“值”可以是一个对象。_数组中的文档
接受的混合
值。而您的示例正是数组中的所做的,其中示例1是$strict=false
,示例2是$strict=true
。
$test = new stdClass();
$test->one = 'one';
$test->two = 'two';
$test->three = 'three';
$array = array($test, $test, $test, $test); // Same object instance
var_dump(in_array($test, $array, true)); // bool(true)
var_dump(in_array($test, $array)); // bool(true)
$newTest = clone $test; // New object instance, will fail strict checks
var_dump(in_array($newTest, $array, true)); // bool(false)
var_dump(in_array($newTest, $array)); // bool(true)
$newTest = new stdClass();
$newTest->one = 'two';
$newTest->two = 'two';
$newTest->three = 'three';
// To ensure that classes with varying values do not satisfy in_array
var_dump(in_array($newTest, $array)); // bool(false)
foreach ($arr as &$member) {
if ($member == $obj) {
return TRUE;
}
}
return FALSE;
foreach ($arr as &$member) {
if ($member === $obj) {
return TRUE;
}
}
return FALSE;