dsfdsfsdf45489 2014-09-12 14:38
浏览 35
已采纳

按另一个数组中的值过滤数组?

I start with two arrays. The first is long and consists of potential ids, but the ids can show up multiple times in the $potential array as a way to increase the probability of that id being selected later.

The second array are ids of persons needing to be paired with somebody from the $potential array. However, the persons needing a partner will show up in the both arrays. So, I need to temporarily remove the elements containing the user id before assigning pairs in order to avoid pairing a person with himself.

$potential = array('105', '105', '105', '2105', '1051');
$users = array('105', '1051');

From this I need to end up with:

$arr1 = Array ( [0] => 105 [1] => 105 [2] => 105 )
$arr2 = Array ( [3] => 2105 [4] => 1051 )

so that I can assign a partner to 105 from $arr2, then recombine the arrays and in the next iteration be able to assign a partner to 1051:

$arr1 = Array ( [4] => 1051 )
$arr2 = Array ( [0] => 105 [1] => 105 [2] => 105 [3] => 2105 )

I've been messing around, but this is the best I've managed to do:

function differs ($v) { global $users; return ($v == current($users)) === true; }

foreach ($users as $value) {
    $arr1 = array_filter($potential, differs);
    $arr2 = array_diff($potential, $arr1);
}

Of course, the above does not work. Any ideas? Am I going about this all wrong? Thanks.

  • 写回答

1条回答 默认 最新

  • doujia2090 2014-09-12 14:53
    关注

    Let me see if I get it straight! You need to loop the users and on each loop, you must have an array with the id's inside the "potencial" array, except the current id. Is that right?

    I was about to ask you this in the comment but I don't have enough reputation :(

    Maybe this code will help, if it's what I'm supposing to be :)

    $potential = array('105', '105', '105', '2105', '1051');
    $users = array('105', '1051');
    
    foreach ($users as $user) {
        $available = array_filter($potential, function($id) use ($user){
            return ($id != $user);
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C