Note that there are some explanatory texts on larger screens.

plurals
  1. POConvert Flat PHP Array to Nested Array based on Array Keys?
    primarykey
    data
    text
    <p>I need to convert a flat array where the array keys indicate the structure into a nested array where the parent element becomes element zero, i.e. in the example:</p> <pre><code>$education['x[1]'] = 'Georgia Tech'; </code></pre> <p>It needs to be converted to:</p> <pre><code>$education[1][0] = 'Georgia Tech'; </code></pre> <p>Here is an example input array:</p> <pre><code>$education = array( 'x[1]' =&gt; 'Georgia Tech', 'x[1][1]' =&gt; 'Mechanical Engineering', 'x[1][2]' =&gt; 'Computer Science', 'x[2]' =&gt; 'Agnes Scott', 'x[2][1]' =&gt; 'Religious History', 'x[2][2]' =&gt; 'Women\'s Studies', 'x[3]' =&gt; 'Georgia State', 'x[3][1]' =&gt; 'Business Administration', ); </code></pre> <p>And here is what the output should be:</p> <pre><code>$education =&gt; array( 1 =&gt; array( 0 =&gt; 'Georgia Tech', 1 =&gt; array( 0 =&gt; 'Mechanical Engineering' ), 2 =&gt; array( 0 =&gt; 'Computer Science' ), ), 2 =&gt; array( 0 =&gt; 'Agnes Scott', 1 =&gt; array( 0 =&gt; 'Religious History' ), 2 =&gt; array( 0 =&gt; 'Women\'s Studies' ), ), 3 =&gt; array( 0 =&gt; 'Georgia State', 1 =&gt; array( 0 =&gt; 'Business Administration' ), ), ); </code></pre> <p>I've banged my head against the wall for hours and still can't get it working. I think I've been looking at it too long. Thanks in advance.</p> <p>P.S. It should be fully nestable, i.e. it should be able to convert a key that looks like this:</p> <pre><code>x[1][2][3][4][5][6] </code></pre> <p>P.P.S. @Joseph Silber had a clever solution but unfortunately using <code>eval()</code> is not an option for this as it's a WordPress plugin and the WordPress community is trying to stamp out the use of <code>eval()</code>.</p>
    singulars
    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