Search code examples
phparraysarray-filter

Filter an Array by Values in Another Array?


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.


Solution

  • 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);
        });
    }