Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active August 31, 2018 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/67dd77697bbd8467dc8b18627cdbd527 to your computer and use it in GitHub Desktop.
Save mtvbrianking/67dd77697bbd8467dc8b18627cdbd527 to your computer and use it in GitHub Desktop.
Group database records - depth 3
<?php
$resources = array(
[
'parent_id' => 1,
'parent' => 'Account',
'module_id' => 11,
'module' => 'User',
'function_id' => 111,
'function' => 'View',
'enabled' => true,
],
[
'parent_id' => 1,
'parent' => 'Account',
'module_id' => 11,
'module' => 'User',
'function_id' => 112,
'function' => 'Edit',
'enabled' => true,
],
[
'parent_id' => 1,
'parent' => 'Account',
'module_id' => 12,
'module' => 'User Role',
'function_id' => 121,
'function' => 'View',
'enabled' => true,
],
[
'parent_id' => 2,
'parent' => 'Asset',
'module_id' => 22,
'module' => 'People',
'function_id' => 221,
'function' => 'View',
'enabled' => true,
],
[
'parent_id' => 2,
'parent' => 'Asset',
'module_id' => 22,
'module' => 'People',
'function_id' => 222,
'function' => 'Create',
'enabled' => false,
],
[
'parent_id' => 2,
'parent' => 'Asset',
'module_id' => 22,
'module' => 'People',
'function_id' => 223,
'function' => 'Edit',
'enabled' => false,
],
);
$components = [];
foreach($resources as $resource) {
$parent_idx = array_search($resource['parent_id'], array_column($components, 'c_id'));
if(is_numeric($parent_idx)) {
$module_idx = array_search($resource['module_id'], array_column($components[$parent_idx]['modules'], 'm_id'));
if(is_numeric($module_idx)) {
$permission = array(
'p_id' => $resource['function_id'],
'name' => $resource['function'],
'enabled' => $resource['enabled'],
);
$components[$parent_idx]['modules'][$module_idx]['permissions'][] = $permission;
continue;
}
$module = array(
'm_id' => $resource['module_id'],
'name' => $resource['module'],
);
$components[$parent_idx]['modules'][] = $module;
$permission = array(
'p_id' => $resource['function_id'],
'name' => $resource['function'],
'enabled' => $resource['enabled'],
);
// Add permission to current module
$module_idx = count($components[$parent_idx]['modules']) - 1;
$components[$parent_idx]['modules'][$module_idx]['permissions'][] = $permission;
continue;
}
$component = array(
'c_id' => $resource['parent_id'],
'name' => $resource['parent'],
);
$module = array(
'm_id' => $resource['module_id'],
'name' => $resource['module'],
);
$permission = array(
'p_id' => $resource['function_id'],
'name' => $resource['function'],
'enabled' => $resource['enabled'],
);
$module['permissions'][] = $permission;
$component['modules'][] = $module;
$components[] = $component;
}
print json_encode(['components' => $components]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment