【发布时间】:2016-02-11 02:14:18
【问题描述】:
我有这两个数组:
1:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Type 1
[rate] => 100.00
)
[1] => stdClass Object
(
[id] => 2
[name] => Type 2
[rate] => 75.00
)
[2] => stdClass Object
(
[id] => 3
[name] => Type 3
[rate] => 50.00
)
[3] => stdClass Object
(
[id] => 4
[name] => Type 4
[rate] => 50.00
)
)
2:
Array
(
[0] => stdClass Object
(
[name] => Type 1
[rate] => 125
)
[1] => stdClass Object
(
[name] => Type 2
[rate] => 85
)
[2] => stdClass Object
(
[name] => Type 3
[rate] => 65
)
)
我需要做的是比较两个数组,并将第一个数组中的缺失项附加到第二个数组。这将始终是第一个数组比第二个数组包含更多项目的情况。
我尝试过使用类似的东西:
$result = array_udiff($array1,$array2,
function ($obj_a, $obj_b) {
return $obj_a->name - $obj_b->name;
}
);
但它只是返回一个空数组
【问题讨论】:
-
return $obj_a->name - $obj_b->name;中的减号是这里出现的错字吗?应该有一个==。 -
不清楚什么是缺少的物品。你只关心
name成员的对象不同吗? -
您的问题需要澄清,因为您的示例不清楚。您的第一个数组有一个名称 = 'Type 1',比率为 100.00,而第二个数组有一个 'Type 1',比率为 125。什么构成应附加到 array2 的“新”元素?
-
@gview 值在这种情况下无关紧要。也许我应该使用数组键来比较差异
-
如果对象所在的数组相同,可以使用array_merge。