我的应用程序中有以下代码,它将按字母顺序显示主题列表,并按每个部分块中的第一个标签名称拆分它们。
例如:
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
因为我已经拆分了数组......
任何人都可以帮忙吗?
如果我调试 $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'
)
)
),...