Simple one, but still can't figure out.
I have two arrays of slightly different structures.
The first array contains members (as first level indexes, e.g. 4, 2) and their document ids (as second level indexes, e.g. 2, 3) and department tags for those documents:
array (
4 =>
array (
2 => 'support',
),
2 =>
array (
3 => 'billing',
),
)
The second array's first level index doesn't have any meaning, so could be get rid of. However, the second level index contains member ids (e.g. 4, 2) and department tags those members opened access to (the current user):
array (
0 =>
array (
4 =>
array (
'support' => 'support',
'billing' => 'billing',
),
),
1 =>
array (
2 =>
array (
'support' => 'support',
),
),
)
So I am trying to compile a list of documents that should be displayed to the current user.
For example, since member #4 has given access to support and billing the current user should be able to see document #2 (tagged as support) from that member.
And because member #2 has given access to only support tagged documents, the current user should not be able to see document #3 (tagged as billing).
So the above example should give only:
array(2)
How do I generate the final array of documents in PHP comparing two arrays?
It's possible to do what you want with loops and searches, but I'd consider this data structure unmaintainable and aim for changing it in the first place. Well, sometimes you can't, so here's how I'd do it:
$documents_data =[
4 => [2 => 'support'],
2 => [3 => 'billing']
];
$access_data = [
[4 => ['support' => 'support', 'billing' => 'billing']],
[2 => ['support' => 'support']]
];
// You need current user's data so having his id
// extract his access rights from second array
$user_id = 4;
function userData($user_id, $access_table) {
$access = [];
foreach ($access_table as $user_acc) {
if (key($user_acc) !== $user_id) { continue; }
$access = reset($user_acc);
break;
}
return [
'id' => $user_id,
'access' => $access
];
}
$user = userData($user_id, $access_data);
// Filter out documents (if any) not matching user's access rights
function userDocuments($user, $docs) {
if (empty($docs[$user['id']])) { return []; }
return array_filter(
$docs[$user['id']],
function ($doc_type) use ($user) {
return isset($user['access'][$doc_type]);
}
);
}
$allowed_docs = userDocuments($user, $documents_data);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments