Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active August 7, 2018 20:35
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/22087c745609b5a69a2859870b78fe90 to your computer and use it in GitHub Desktop.
Save mtvbrianking/22087c745609b5a69a2859870b78fe90 to your computer and use it in GitHub Desktop.
Group database records
<?php
$resources = array(
[
'parent_id' => 1,
'parent' => 'Account',
'module_id' => 11,
'module' => 'User',
'enabled' => true,
],
[
'parent_id' => 1,
'parent' => 'Account',
'module_id' => 12,
'module' => 'User Role',
'enabled' => false,
],
[
'parent_id' => 2,
'parent' => 'Asset',
'module_id' => 21,
'module' => 'Device',
'enabled' => true,
],
[
'parent_id' => 2,
'parent' => 'Asset',
'module_id' => 22,
'module' => 'People',
'enabled' => true,
],
[
'parent_id' => 2,
'parent' => 'Account',
'module_id' => 23,
'module' => 'Modules',
'enabled' => false,
],
);
$components = [];
foreach($resources as $resource) {
$parent_idx = array_search($resource['parent_id'], array_column($components, 'id'));
if(is_numeric($parent_idx)) {
$module = array(
'id' => $resource['module_id'],
'name' => $resource['module'],
'enabled' => $resource['enabled'],
);
$components[$parent_idx]['modules'][] = $module;
continue;
}
$component = array(
'id' => $resource['parent_id'],
'name' => $resource['parent'],
);
$module = array(
'id' => $resource['module_id'],
'name' => $resource['module'],
'enabled' => $resource['enabled'],
);
$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