我有这两个数组:
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;
}
);
但它只返回一个空数组
答案 0 :(得分:0)
此?
<?php
$arr1 = array(
(object)array("id"=>1,"name"=>"type 1","rate"=>100.00),
(object)array("id"=>2,"name"=>"type 2","rate"=>75.00),
(object)array("id"=>3,"name"=>"type 3","rate"=>50.00),
(object)array("id"=>4,"name"=>"type 4","rate"=>50.00)
);
$arr2 = array(
(object)array("name"=>"type 1","rate"=>125),
(object)array("name"=>"type 2","rate"=>85),
(object)array("name"=>"type 3","rate"=>65)
);
for($i=0;$i<sizeof($arr1);$i++){
$count=0;
for($j=0;$j<sizeof($arr2);$j++){
if($arr1[$i]->name == $arr2[$j]->name){
$count++;
}
}
if($count==0){
array_push($arr2,(object)array("name"=>$arr1[$i]->name,"rate"=>$arr1[$i]->rate));
}
}
print_r($arr2);
?>
答案 1 :(得分:0)
不需要复杂,假设您允许数组包含相同类型和结构的对象。我们没有足够的上下文来解释是否有充分的理由你不能理解。
//$array1 original array
//$array2 target array
$array2 = array_merge($array1, $array2);