Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to unflatten array in PHP using dot notation
    text
    copied!<p>I have php array structure like this:</p> <pre><code>array( 'servicemanagement.scheduler.events.edit' =&gt; 'Edit', 'servicemanagement.scheduler.events.delete' =&gt; 'Delete', 'servicemanagement.scheduler.events' =&gt; 'Events', 'servicemanagement.scheduler' =&gt; 'Scheduler', 'servicemanagement.subscribers' =&gt; 'Subscribers', 'servicemanagement.subscribers.index' =&gt; 'Index', 'servicemanagement' =&gt; 'Service management', ); </code></pre> <p>And I would like to convert is to multidimensional array like:</p> <pre><code>array( 'servicemanagement' =&gt; array( 'id' =&gt; 'servicemanagement', 'title' =&gt; 'Service Management', 'children' =&gt; array( 'scheduler' =&gt; array( 'id' =&gt; 'servicemanagement.scheduler', 'title' =&gt; 'Scheduler', 'children' =&gt; array( 'events' =&gt; array( 'id' =&gt; 'servicemanagement.scheduler.events', 'title' =&gt; 'Events', 'children' =&gt; array( 'edit' =&gt; array( 'id' =&gt; 'servicemanagement.scheduler.events.edit', 'title' =&gt; 'Edit', 'children' =&gt; array(), ), 'delete' =&gt; array( 'id' =&gt; 'servicemanagement.scheduler.events.delete', 'title' =&gt; 'Delete', 'children' =&gt; array(), ), ), ), ), ), 'subscribers' =&gt; array( 'id' =&gt; 'servicemanagement.subscribers', 'title' =&gt; 'Subscribers', 'children' =&gt; array( 'index' =&gt; array( 'id' =&gt; 'servicemanagement.subscribers.index', 'title' =&gt; 'Index', ) ), ), ), ), ); </code></pre> <p>I have checked some answers already like this one: <a href="https://stackoverflow.com/questions/13359681/how-to-set-a-deep-array-in-php?answertab=active#tab-top">How to set a deep array in PHP</a></p> <p>But it seems that i could not manage to clear up the writing on top of the arrays and the last record 'servicemanagement' removes all of the previous records.</p> <p>The function that is used there is </p> <pre><code>function setArray(&amp;$array, $keys, $value) { $keys = explode(".", $keys); $current = &amp;$array; foreach($keys as $key) { $current = &amp;$current[$key]; } $current = $value; } </code></pre> <p>Another function that I have found but it is not doing the expected result is:</p> <pre><code>function unflatten($array,$prefix = '') { $result = array(); foreach($array as $key=&gt;$value) { if (!empty($prefix)) { $key = preg_replace('#^'.preg_quote($prefix).'#','',$key); } if (strpos($key,'.') !== false) { parse_str('result['.str_replace('.','][',$key)."]=".$value); } else { $result[$key] = $value; } } return $result; } </code></pre> <p>It is an option to use recursion to unflatten this array since the end format is the same for all records.</p> <p>May anyone give me a tip ot this one?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload