gpt4 book ai didi

PHP:将数据数组拆分为字母顺序

转载 作者:行者123 更新时间:2023-12-04 18:21:13 24 4
gpt4 key购买 nike

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

例如:

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'
)
)
),...

最佳答案

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

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

$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:将数据数组拆分为字母顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10635260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com