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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器