从复杂数组创建简单数组

时间:2018-05-14 20:22:16

标签: php arrays wordpress

我有以下两个数组:

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 ( [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 ) )

我正在尝试比较两个数组,以确定[term_id]值是否匹配:

$match = array_intersect($array_one_ids, $array_two_ids);
if( count($match) > 0) {  echo 'we have a match!';  }

我的问题是,如何在上述每个数组中创建只有$array_one_ids值的数组(由$array_two_idsterm_id定义),以便$array_one_ids = array(36, 38)$array_two_ids会= array(36)

2 个答案:

答案 0 :(得分:2)

您可以在每个输入数组上使用array_column将它们转换为term_id的数组。

$match = array_intersect(
    array_column($arrayOne, 'term_id'),
    array_column($arrayTwo, 'term_id')
);

对于array_column不处理对象数组的旧版PHP,您可以使用array_map来提取该属性。

$match = array_intersect(
    array_map(function($term) { return $term->term_id; }, $arrayOne),
    array_map(function($term) { return $term->term_id; }, $arrayTwo)
);

另外,您不必计算$match来检查结果,因为数组在if条件下评估为truefalse,具体取决于它是否为&#39} ;空的。 (See "converting to boolean"。)

if ($match) {  echo 'we have a match!';  }

答案 1 :(得分:1)

如果您不需要整个WP_Term对象,则可以在检索时将fields参数添加到查询中,以仅检索术语的ID。

例如:

$queryOne = new WP_Term_Query(array(
    'taxonomy' => 'emp_unit_name',
     ... // The other args of your query,
    'fields' => 'ids'
));

然后您可以访问ID($query->terms):

array(36, 38);

一旦有了这两个查询,你就可以:

$match = array_intersect($queryOne->terms, $queryTwo->terms);

但是,如果你需要整个对象,你可以像@Don't Panic的答案那样做。

相关问题