【问题标题】:Get the intersect of tables获取表格的交集
【发布时间】:2017-06-09 01:26:21
【问题描述】:

我有一个问题。所以我有这个数组:

$a_list_id = array(
   0 => 1234
   1 => 739
   3 => 538
);

还有这个数组:

$a_users = array(
    0 => array(
        id => 15627,
        name => test
    ),
    1 => array(
        id => 1234,
        name => test1
    ),
    2 => array(
        id => 739,
        name => test2
    )
)

结果应该是:

$a_response = array(
    0 => array(
       id => 1234,
       name => test1 
    )
)

因为 id 1234 在两个数组中。 我尝试使用 array_intersect 但不起作用。你能帮帮我吗?

【问题讨论】:

  • 739 也在两个数组中,但结果不是预期的?

标签: php php-5.4 array-intersect


【解决方案1】:

array_intersect 只有在两个数组的值都可以转换为相同类型时才会产生有用的结果。你有一个整数数组和另一个数组数组,它​​们永远无法匹配,所以 intersect 永远是空的

如果你想要数组之间的交集,那么你有两个选择:

  • 索引数组,以便它们的键是您想要相交的值并使用array_intersect_key
  • 使用array_uintersect 和一个知道被比较数组结构的回调函数实现您自己的数组比较逻辑

前者的例子:

$a_list_id = array(
   1234 => 1234
   739 => 739
   538 => 538
);

$a_users = array(
    15627 => array(
        id => 15627,
        name => test
    ),
    1234 => array(
        id => 1234,
        name => test1
    ),
    739 => array(
        id => 739,
        name => test2
    )
)

var_dump (array_intersect_key ($a_users, $a_list_id));

后者的例子:

var_dump (array_uintersect ($a_users, $a_list_id, function ($user, $id) {
    return $user ["id"] - $id; // Result should be 0 if they match, as per documentation
}))

*在一个值为整数0,另一个为空数组的情况下,它们可以认为是相同的,但这不是很有用

【讨论】:

    【解决方案2】:

    您是否尝试过使用array_intersect_uassochttp://php.net/manual/en/function.array-intersect-uassoc.php

    function compare_ids($a, $b)
    {
        return $a - $b['id'];
    }
    
    print_r(array_intersect_uassoc($a_list_id, $a_users, "compare_ids"));
    

    【讨论】:

    • 这不是真正的答案,而是评论。
    • @GordonM 抱歉,对于后期实施示例。
    • 仅供参考,如果两个值相同,则回调应返回 0,否则返回非零结果。
    【解决方案3】:

    使用 array_search() 函数尝试以下代码:

    $a_list_id = array(1234, 538,739);
    
    $a_users = array(
     array(
        'id'=> 15627,
        'name' => 'test'
    ),
     array(
        'id' => 1234,
        'name' => 'test1'
    ),
     array(
        'id' => 739,
        'name' => 'test2'
    )
    );
    
    foreach($a_users as $a_user){
      if (in_array($a_user['id'], $a_list_id)) {
         $a_response[array_search($a_user['id'], $a_list_id)] = $a_user;
      }
    }
    
    print_r($a_response);
    

    【讨论】:

      【解决方案4】:

      只需使用循环:

      $a_response = array();
      foreach ($a_users as $array) {
          if (in_array($array['id'], $a_list_id)) {
              $a_response []= $a_users;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-04
        • 2017-12-31
        • 1970-01-01
        • 2016-02-29
        相关资源
        最近更新 更多