Reputation: 26107
I have the following two arrays:
userStatus
---------------
Array
(
[0] => Array
(
[Username] => [email protected]
[Status] => Active
)
[1] => Array
(
[Username] => [email protected]
[Status] => Terminated
)
[2] => Array
(
[Username] => [email protected]
[Status] => OnVacation
)
)
users
------
Array
(
[0] => [email protected]
[1] => [email protected]
[2] => [email protected]
)
I want to write a snippet that brings up an array of all userStatus entries that do not match on Username field in the users Array.
How can I do this? I don't seem to find an efficient and fast way to do this in PHP.
Thanks
Upvotes: 1
Views: 230
Reputation: 42458
This answer was originally me being facetious, and I would suggest that safarov's answer is the clearest, but here's a solution with a custom callback to array_diff:
$userStatus = array(
array('Username' => '[email protected]', 'Status' => 'Active'),
array('Username' => '[email protected]', 'Status' => 'Terminated'),
array('Username' => '[email protected]', 'Status' => 'OnVacation'),
);
$users = array(
'[email protected]',
);
var_dump(array_udiff($userStatus, $users, function($status, $user) {
return $status['Username'] !== $user;
}));
Upvotes: 0
Reputation: 1253
With your current arrays there is no logical way to avoid traversing $users for every $userStatus which would use exponential time O(n^2) and could get out of hand.
If instead you could convert $users to a hash (perhaps array_flip) then you could do it in linear time O(n).
$usersHash = array_flip($users);
foreach ($userStatuses as $status) {
if (!array_key_exists($status['username'], $usersHash)) {
// do something with the user
}
}
Check out this related post for some information regarding time complexity of common PHP functions.
Upvotes: 0
Reputation: 7804
$result = array();
foreach($userStatus as $value) {
if(!in_array($value['Username'], $users) {
$result[] = $value;
}
}
print_r($result);
Upvotes: 2