dongyukui8330 2018-05-14 20:22
浏览 115
已采纳

从复杂数组创建简单数组

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)?

  • 写回答

2条回答 默认 最新

  • dongliyi967823 2018-05-14 20:25
    关注

    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!';  }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题