2

I have a piece of string that looks like this, which defines the structure of my array (generated from selected options in a JSTree):

Dashboard_Tabs_Summary<#>Dashboard_Sections_Default_View<#>Clients_Tabs_Summary<#>Clients_Tabs_Quote History<#>Clients_Tabs_Order History<#>Clients_Tabs_Notes<#>Clients_Tabs_Contacts<#>Clients_Sections_Default_Create<#>Clients_Sections_Default_View<#>Clients_Sections_Default_Edit<#>Clients_Sections_Default_Delete<#>Dashboard_Tabs<#>Dashboard_Sections_Default<#>Dashboard_Sections<#>Dashboard<#>Clients_Tabs<#>Clients_Sections_Default<#>Clients_Sections<#>Clients

If I explode this string by <#>, I end up with these lines (sorted in logical order):

Dashboard
Dashboard_Tabs
Dashboard_Tabs_Summary
Dashboard_Sections
Dashboard_Sections_Default
Dashboard_Sections_Default_View
Clients
Clients_Tabs
Clients_Tabs_Summary
Clients_Tabs_Quote History
Clients_Tabs_Order History
Clients_Tabs_Notes
Clients_Tabs_Contacts
Clients_Sections
Clients_Sections_Default
Clients_Sections_Default_Create
Clients_Sections_Default_View
Clients_Sections_Default_Edit
Clients_Sections_Default_Delete

Is there a way to go from the above into an array structure like this:

enter image description here

Here's my attempt, but it's not working quite right:

<?php

$permissions = 'Dashboard_Tabs_Summary<#>Dashboard_Sections_Default_View<#>Clients_Tabs_Summary<#>Clients_Tabs_Quote History<#>Clients_Tabs_Order History<#>Clients_Tabs_Notes<#>Clients_Tabs_Contacts<#>Clients_Sections_Default_Create<#>Clients_Sections_Default_View<#>Clients_Sections_Default_Edit<#>Clients_Sections_Default_Delete<#>Dashboard_Tabs<#>Dashboard_Sections_Default<#>Dashboard_Sections<#>Dashboard<#>Clients_Tabs<#>Clients_Sections_Default<#>Clients_Sections<#>Clients';
$permissions = explode('<#>', $permissions);

$data = [];
foreach ($permissions as $permission) {
    $p = explode('_', $permission);
    @list($p0, $p1, $p2, $p3) = $p;
    switch (sizeof($p))
    {
        case 4:
            $data[$p0][$p1][$p2][$p3] = null;
            break;

        case 3:
            $data[$p0][$p1][$p2] = null;
            break;
    }
}

echo '<pre>';
print_r($data);

?>

1 Answer 1

2

You can use a reference to create the nested array:

$data = array();

foreach(explode('<#>', $permissions) as $permission) {
    $path = explode('_', $permission);
    $temp =& $data;
    foreach($path as $key) {
        $temp =& $temp[$key];
    }
}
print_r($data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.