我的應用程序中有以下代碼,它將按字母順序顯示主題列表,並按每個區塊中的第一個標記名稱分割它們。PHP:按字母順序將數據拆分爲
例如:
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變量只是存儲標題和其他所需的數據。我也想展示TopicPost在<em>
算,因此,如果一個主題有4個相關帖子顯示<em>4</em>
目前國內做我在做什麼給出了錯誤:Fatal error: Cannot use string offset as an array
,因爲我已經分裂陣列...
任何人都可以幫忙嗎?
如果我調試$主題數組我得到如下:
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'
)
)
),...
任何更新這個好嗎? – Cameron