Home > Enterprise >  recursive function to join accounts with at least one common user in PHP
recursive function to join accounts with at least one common user in PHP

Time:10-30

I need a recursive function to group accounts based on user groups already in the same group.

But :

If grp1 => ['a', 'b'] and grp2 => ['b', 'c'] Here b make the link with grp1 and grp2 If I have another grp248 => ['a' , 'z'], as a is present in grp1 a link exist for grp1 grp2 and grp248 even if group2 has nothing in common with group248.

make chains like this person knows this person who knows this person etc ...

//input
$data = [
    'account1_id' => ['user1_id', 'user2_id'],
    'account2_id' => ['user2_id', 'user8_id'],
    'account4_id' => ['user15_id', 'user16_id'],
    'account5_id' => ['user15_id', 'user16_id'],
    'account7_id' => ['user24_id', 'user25_id', 'user26_id', 'user27_id'],
    'account8_id' => ['user29_id', 'user30_id', 'user8_id'],
    ];

//ouput need
$data = [
    0 => ['account1_id', 'account2_id', 'account8_id'],
    1 => ['account4_id', 'account5_id'],
    2 => ['account7_id'],
];

CodePudding user response:

Find it :

$usersArray = array();
#first reverse array with user as key
foreach ($data as $idAcc => $users) {
    foreach ($users as $idUser) {
        if (!key_exists($idUser, $usersArray)) {
            $usersArray[$idUser] = array($idAcc);
        } elseif (!in_array($idAcc, $usersArray[$idUser])) {
            $usersArray[$idUser][] = $idAcc;
        }
    }
}

# make reduction
$newData = array();
foreach ($usersArray as $idUSer => $accountsId) {
    foreach ($accountsId as $accountId) {
        $addAsNew=true;
        foreach ($newData as $index => $accountsTab) {
            if (in_array($accountId, $accountsTab)) {
                $addAsNew=false;
                $newData[$index]=array_unique(array_merge($newData[$index],$accountsId));
                break ;
            }
        }
        if($addAsNew){
            $newData[]=$accountsId;
        }
    }
}
var_dump($newData);
  • Related