php - Comparing two object arrays with array_udiff -
array 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)
array 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)
i'm trying extract values of array 1 not appear in array 2:
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');
but result return common value: tag 1. expect tag 4 , tag 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)
as alternative, gather tags needed excluded first. after filter thru array_filter
, desired result. rough example:
$tags = array(); foreach($post_tags_result $t) { $tags[] = $t->tag; // gather tags } // filter array using gathered tags $result = array_filter($tags_result, function($v) use($tags){ return !in_array($v->tag, $tags); });
Comments
Post a Comment