Note that there are some explanatory texts on larger screens.

plurals
  1. POConvert non-nested and bracketed array to nested array
    primarykey
    data
    text
    <p>I'm in PHP and I've got an array that looks like this. A single dimension array whose keys are bracketed strings.</p> <pre><code>array( 'matrix[min_rows]' =&gt; '0', 'matrix[max_rows]' =&gt; '', 'matrix[col_order][]' =&gt; 'col_new_1', 'matrix[cols][col_new_0][type]' =&gt; 'text', 'matrix[cols][col_new_1][type]' =&gt; 'text', 'matrix[cols][col_new_0][label]' =&gt; 'Cell 1', 'matrix[cols][col_new_1][label]' =&gt; 'Cell 2', 'matrix[cols][col_new_0][name]' =&gt; 'cell_1', 'matrix[cols][col_new_1][name]' =&gt; 'cell_2', 'matrix[cols][col_new_0][instructions]' =&gt; '', 'matrix[cols][col_new_1][instructions]' =&gt; '', 'matrix[cols][col_new_0][width]' =&gt; '33%', 'matrix[cols][col_new_1][width]' =&gt; '', 'matrix[cols][col_new_0][settings][maxl]' =&gt; '', 'matrix[cols][col_new_0][settings][fmt]' =&gt; 'none', 'matrix[cols][col_new_0][settings][content]' =&gt; 'all', 'matrix[cols][col_new_1][settings][maxl]' =&gt; '140', 'matrix[cols][col_new_1][settings][multiline]' =&gt; 'y', 'matrix[cols][col_new_1][settings][fmt]' =&gt; 'none', 'matrix[cols][col_new_1][settings][content]' =&gt; 'all', ) </code></pre> <p>Is there any easy way to convert that to a normal nested array, ie:</p> <pre><code>array( 'matrix' =&gt; array( 'min_rows' =&gt; '0', 'max_rows' =&gt; '', 'col_order' =&gt; array('col_new_1'), 'cols' =&gt; array( 'col_new_0' =&gt; array( 'type' =&gt; 'text', 'label' =&gt; 'Cell 1', ....etc.... </code></pre> <p>This is my current solution, but I was wondering if there's something more native or efficient:</p> <pre><code>foreach ($decoded_field_type_settings as $key =&gt; $value) { if (preg_match_all('/\[(.*?)\]/', $key, $matches)) { $new_key = substr($key, 0, strpos($key, '[')); if ( ! isset($field_type_settings[$new_key])) { $field_type_settings[$new_key] = array(); } $array =&amp; $field_type_settings[$new_key]; $count = count($matches[1]) - 1; foreach ($matches[1] as $i =&gt; $sub_key) { if ( ! $sub_key) { if ($i &lt; $count) { $array[] = array(); } else { $array[] = $value; } } else { if ( ! isset($array[$sub_key])) { if ($i &lt; $count) { $array[$sub_key] = array(); } else { $array[$sub_key] = $value; } } } if ($i &lt; $count) { $array =&amp; $array[$sub_key]; } } } else { $field_type_settings[$key] = $value; } } </code></pre> <p>UPDATE: I posted an answer below.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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