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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大