PHP: Split array of data into alphabetical order
<p>I have the following code in my app that will show a list of topics in alphabetical order and split them by the first tag name in each section block.</p>

<p>e.g:</p>

<pre><code>A
animal
amazing

B
bat
baseball
</code></pre>

<p>The code is as follows:</p>

<pre><code>&lt;?php

    foreach($topics as $currentTopic):
        $thisLetter = strtoupper($currentTopic['Topic']['title'][0]);
        $sorted[$thisLetter][] = $currentTopic['Topic']['title'];
        unset($thisLetter);
    endforeach;

    foreach($sorted as $key=&gt;$value):

        echo '&lt;h3 class="alpha"&gt;&lt;span&gt;'.$key.'&lt;/span&gt;&lt;/h3&gt;';
        echo '&lt;ol class="tags main"&gt;';

        foreach($value as $thisTopic):

            echo '&lt;li class="tag"&gt;&lt;em&gt;0&lt;/em&gt;';
            echo $this-&gt;Html-&gt;link('&lt;strong&gt;'.$thisTopic['Topic']['title'].'&lt;/strong&gt;',
                        array('controller'=&gt;'topics','action'=&gt;'view','slug'=&gt;$thisTopic['Topic']['slug']),
                        array('escape'=&gt;false,'rel'=&gt;'tag'));
            echo '&lt;/li&gt;';
        endforeach;

        echo '&lt;/ol&gt;';

    endforeach;

    ?&gt;
</code></pre>

<p>However as I have now split the array, I'm finding it difficult to access the other data in the array such as the topic slug used for the link as the $thisTopic variable just stores the title and the other required data. I also want to show the TopicPost count in the <code>&lt;em&gt;</code> as well so if a Topic has 4 related Posts show <code>&lt;em&gt;4&lt;/em&gt;</code></p>

<p>Currently doing what I'm doing gives the error: <code>Fatal error: Cannot use string offset as an array</code> because I've split the array...</p>

<p>Can anyone help?</p>

<p>If I debug the $topics array I get the following:</p>

<pre><code>array(
    (int) 0 =&gt; array(
        'Topic' =&gt; array(
            'id' =&gt; '5',
            'title' =&gt; 'amazing',
            'slug' =&gt; 'amazing'
        ),
        'TopicPost' =&gt; array(
            (int) 0 =&gt; array(
                'id' =&gt; '9',
                'topic_id' =&gt; '5',
                'post_id' =&gt; '101'
            )
        )
    ),
    (int) 1 =&gt; array(
        'Topic' =&gt; array(
            'id' =&gt; '4',
            'title' =&gt; 'amazingness',
            'slug' =&gt; 'amazingness'
        ),
        'TopicPost' =&gt; array(
            (int) 0 =&gt; array(
                'id' =&gt; '8',
                'topic_id' =&gt; '4',
                'post_id' =&gt; '100'
            ),
            (int) 1 =&gt; array(
                'id' =&gt; '12',
                'topic_id' =&gt; '4',
                'post_id' =&gt; '101'
            ),
            (int) 2 =&gt; array(
                'id' =&gt; '4',
                'topic_id' =&gt; '4',
                'post_id' =&gt; '119'
            )
        )
    ),...
</code></pre>
