简体   繁体   中英

Compare two arrays remove duplicates

I'm building management system with three roles (admin,supervisor,basic) on the user assignment page which would be a checklist where an admin can assign a basic user to a supervisor.

I have two arrays, the first array is supervisors that have been assigned to "manage" that specific basic user, and the second would be just all supervisors. My goal is to remove the already assigned supervisors from the all supervisor array.

//example

$supervisors['all'] = [
         ['id'=>'1','first'=>'john','last'=>'doe'],
         ['id'=>'2','first'=>'jane','last'=>'doe']
];
$supervisors['assigned'] = [
         ['id'=>'2','first'=>'jane','last'=>'doe']
];

//so the result I'm looking for is

$supervisors['all'] = [
         ['id'=>'1','first'=>'john','last'=>'doe'],
];
$supervisors['assigned'] = [
         ['id'=>'2','first'=>'jane','last'=>'doe']
];

Try this with array_filter .

// here we collect all the "assigned" ids in a plain array
$assignedSvsIds = array_column($supervisors['assigned'], 'id');
// then use it in a filter function
$supervisors['all'] = array_filter(
    $supervisors['all'], 
    function($sv) use ($assignedSvsIds) {
        // if id is in 'assigned', it'll be filtered out, otherwise - kept
        return !in_array($sv['id'], $assignedSvsIds, true);
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM