I'm trying to create a very specific data structure with simple arrays but have got into some issues that I have troubles solving.
I have an empty array and one that I want to build the empty array from.
$roles = [];
$role_structure = ['domain', 'role_category', 'role'];
What I want it to do is to build an array structure from that there the last entry of the role_structure
is set to true
and the rest is the key value.
I've written a recursive function to accomplish this:
static function recursive_append_children($arr, $arr_to_append) {
$shifted_val = array_shift($arr_to_append);
if (array_key_exists($shifted_val, $arr)) {
$arr[$shifted_val] = static::recursive_append_children($arr[$shifted_val], $arr_to_append);
} else {
$arr[$shifted_val] = count($arr_to_append) > 0 ? static::recursive_append_children($arr,
$arr_to_append) : true;
}
return $arr;
}
Which works fine if the first array is empty. But if there already is a defined role_structure in the $roles
array I just want it to add the new role to the existing array.
So, for example I can send run the first example and it will give me the following output:
['domain' => ['role_category' => ['role' => true]]]
But if I send in the result array as the first parametar to the function above and with another second parameter array that looks like this ['domain', 'another_role_category', 'another_role']
it will produce the following array:
['domain' => [
'role_category' => ['role' => true],
'another_role_category' => [
'role_category' => ['role' => true],
'another_role' => true
]
]
As you surely understand, I don't want two of the role_category
and I want to be able to update the first array without duplicating the values. I hope you understand my issue and I am grateful for all help.
Thanks.