数组1:$ tags_result
array (size=4)
0 =>
object(stdClass)[8]
public 'id_tag' => string '2' (length=1)
public 'tag' => string 'tag 1' (length=5)
1 =>
object(stdClass)[9]
public 'id_tag' => string '5' (length=1)
public 'tag' => string 'tag 4' (length=5)
2 =>
object(stdClass)[10]
public 'id_tag' => string '6' (length=1)
public 'tag' => string 'tag 7' (length=5)
3 =>
object(stdClass)[11]
public 'id_tag' => string '7' (length=1)
public 'tag' => string 'tag 9' (length=5)
数组2:$ post_tags_result
array (size=2)
0 =>
object(stdClass)[5]
public 'id_tag' => string '2' (length=1)
public 'tag' => string 'tag 1' (length=5)
1 =>
object(stdClass)[6]
public 'id_tag' => string '6' (length=1)
public 'tag' => string 'tag 7' (length=5)
我尝试提取未出现在数组2中的数组1的值:
function foo($tags_result, $post_tags_result){
return $tags_result->id_tag != $post_tags_result->id_tag;
}
$difference_tags = array_udiff($tags_result, $post_tags_result, 'foo');
但结果返回一个共同的值:标签1.我希望只标记4和标记9.
array (size=3)
0 =>
object(stdClass)[8]
public 'id_tag' => string '2' (length=1)
public 'tag' => string 'tag 1' (length=5)
1 =>
object(stdClass)[9]
public 'id_tag' => string '5' (length=1)
public 'tag' => string 'tag 4' (length=5)
3 =>
object(stdClass)[11]
public 'id_tag' => string '7' (length=1)
public 'tag' => string 'tag 9' (length=5)
答案 0 :(得分:4)
作为替代方案,您可以收集首先需要排除的所有标签。然后,您可以通过array_filter
过滤它,并获得所需的结果。粗略的例子:
$tags = array();
foreach($post_tags_result as $t) {
$tags[] = $t->tag; // gather all tags
}
// filter array using gathered tags
$result = array_filter($tags_result, function($v) use($tags){
return !in_array($v->tag, $tags);
});
答案 1 :(得分:0)
从手册:
如果第一个参数被认为分别小于,等于或大于第二个参数,则比较函数必须返回小于,等于或大于零的整数。
因此,您应该使用diff来删除相等的项目,而不是布尔比较。由于您要比较数值,因此您应该执行以下操作:
$ php -a
php > $a = [['id'=>1],['id'=>2],['id'=>3],['id'=>4]];
php > $b = [['id'=>1],['id'=>4]];
php > $c = array_udiff($a, $b, function($a, $b){
return $a['id'] - $b['id'];
});
php > print_r($c);
Array
(
[1] => Array
(
[id] => 2
)
[2] => Array
(
[id] => 3
)
)
在你的情况下:
$difference_tags = array_udiff($tags_result, $post_tags_result, function(($a1, $a2){
return $a1->id_tag - $q2->id_tag;
}));