I have the following two arrays:
Array One
Array ( [0] => WP_Term Object ( [term_id] => 36 [name] => Fractions [slug] => fractions-cat [term_group] => 0 [term_taxonomy_id] => 36 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 11 [filter] => raw [term_order] => 0 )
[1] => WP_Term Object ( [term_id] => 38 [name] => Geometry [slug] => geometry [term_group] => 0 [term_taxonomy_id] => 38 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 2 [filter] => raw [term_order] => 0 )
)
Array Two
Array ( [0] => WP_Term Object ( [term_id] => 36 [name] => Fractions [slug] => fractions-cat [term_group] => 0 [term_taxonomy_id] => 36 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 11 [filter] => raw [term_order] => 0 ) )
I'm trying to compare the two arrays to find if there are any matches for the [term_id] values as such:
$match = array_intersect($array_one_ids, $array_two_ids);
if( count($match) > 0) { echo 'we have a match!'; }
My question is, how can I create arrays (defined by $array_one_ids
and $array_two_ids
) of just the term_id
values in each of the above arrays such that $array_one_ids
would = array(36, 38)
and $array_two_ids
would = array(36)
?
You can use array_column
on each of the input arrays to convert them to arrays of term_id
.
$match = array_intersect(
array_column($arrayOne, 'term_id'),
array_column($arrayTwo, 'term_id')
);
For older PHP versions where array_column
doesn't handle arrays of objects, you can use array_map
to extract that property.
$match = array_intersect(
array_map(function($term) { return $term->term_id; }, $arrayOne),
array_map(function($term) { return $term->term_id; }, $arrayTwo)
);
Also, you don't have to count $match
to check the result, as an array evaluates to true
or false
in an if condition depending on whether it's empty. (See "converting to boolean".)
if ($match) { echo 'we have a match!'; }
If you do not need the whole WP_Term
object, you can add a fields
parameter to your query when you retrieve it to only retrieve the ids of the terms.
For example:
$queryOne = new WP_Term_Query(array(
'taxonomy' => 'emp_unit_name',
... // The other args of your query,
'fields' => 'ids'
));
Then you can access the ids ($query->terms
):
array(36, 38);
Once you have both queries, you could do:
$match = array_intersect($queryOne->terms, $queryTwo->terms);
However, if you need the whole object, you can do it like @Don't Panic's answer.