PHP:将数据数组拆分为字母顺序
Posted
技术标签:
【中文标题】PHP:将数据数组拆分为字母顺序【英文标题】:PHP: Split array of data into alphabetical order 【发布时间】:2012-05-17 11:53:16 【问题描述】:我的应用程序中有以下代码,它将按字母顺序显示主题列表,并按每个部分块中的第一个标签名称对其进行拆分。
例如:
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】:您收到错误是因为您只存储主题的标题。
我建议存储整个主题信息,而不仅仅是标题:
$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...
【讨论】:
以上是关于PHP:将数据数组拆分为字母顺序的主要内容,如果未能解决你的问题,请参考以下文章