PHP:按字母顺序拆分数据数组

时间:2012-05-17 11:53:17

标签: php

我的应用程序中有以下代码,它将按字母顺序显示主题列表,并按每个部分块中的第一个标记名称进行拆分。

e.g:

A
animal
amazing

B
bat
baseball

代码如下:

<?php

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

    foreach($sorted as $key=>$value):

        echo '<h3 class="alpha"><span>'.$key.'</span></h3>';
        echo '<ol class="tags main">';

        foreach($value as $thisTopic):

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

        echo '</ol>';

    endforeach;

    ?>

然而,由于我现在拆分数组,我发现很难访问数组中的其他数据,例如用于链接的主题slug,因为$ thisTopic变量只存储标题和其他所需数据。我还希望在<em>中显示TopicPost计数,如果主题有4个相关帖子显示<em>4</em>

目前正在做我正在做的事情会产生错误:Fatal error: Cannot use string offset as an array因为我已拆分数组......

有人可以帮忙吗?

如果我调试$ topics数组,我会得到以下内容:

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

1 个答案:

答案 0 :(得分:4)

您收到错误是因为您只存储了主题标题。

我建议存储整个主题信息,而不仅仅是标题:

$orderedTopics= array();
foreach ($topics as $topic) {
  $orderedTopics[strtoupper($topic['Topic']['title'][0])][] = $topic;
}

然后,要显示它:

foreach ($orderedTopics as $section=>$topics) {
  echo $section;
  foreach ($topics as $topic) {
    echo 'Title: ' . $topic['Topic']['title'];
    echo 'Body: ' . $topic['Topic']['body'];
    //etc...
  }
}