这是我的疑问:
try
{
$sql = 'SELECT park_id, name, town, state, country
FROM tpf_parks wHERE ORDER BY name ASC';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching parks: ' . $e->getMessage();
//include 'error.html.php';//
exit();
}
$output = 'Parks Loaded';
//include 'output.html.php';//
foreach ($result as $row)
{
$parklist[] = array(
'park_id' => $row['park_id'],
'name' => $row['name'],
'town' => $row['town'],
'state' => $row['state'],
'country' => $row['country']
);
}
include 'parks.html.php';
这是parks.html.php
<?php foreach ($parklist as $park):?>
<a href="park.php?park_id=<?php echo $park['park_id'];?>">
<h2><?php echo $park['name'];?></h2>
<h3><?php echo $park['town'],',',$park['state'],',',$park['country'];?></h3>
</a>
<hr>
<?php endforeach; ?>
我正在寻找一些可以改变foreach循环的方法,这样我就可以将结果分成按第一个字母排序的组。这样我就可以为每个字母添加一个html锚点,通过单击页面顶部的链接(A B C D E等),用户可以更轻松地找到特定记录。我对如何实现这一目标毫无头绪。
答案 0 :(得分:0)
嗯,除非你使用variable variables,否则它不会是最漂亮的解决方案,这将允许你创建数组并根据一个带字母数组字母的循环来分配它们。
但如果这对你来说太复杂了,那就做这样的事情:
$a = array();
$b = array();
$c = array();
...
foreach ($result as $row)
{
$letter = strtolower(substr($row['name'], 0, 1));
if ($letter == 'a') $a.push($row);
else if($letter == 'b') $b.push($row);
...
}
显然,重复每一封信。
然后,当您遍历数组以进行html创建时,您将必须通过每个字母数组执行foreach()。
答案 1 :(得分:0)
foreach ($result as $row)
{
//add to sub-array with first letter of $row['name']
$parklist[strtolower($row['name'][0]][] = array(
....
//rather then give the whole alphabet with possible empties, check for existing letters:
$letters = array_keys($parklist)
或者,为了多字节环境中的安全性(例如utf-8):
$parklist[mb_strtolower(mb_substr($row['name'],0,1))][]= array(
(假设您有正确的mb_internal_encoding()
)
如果您希望diacretics解析为他们的基地(例如ö
到o
);
$parklist[iconv('whateveryourinputcharsetis','ASCII//TRANSLIT',mb_strtolower(mb_substr($row['name'],0,1)))][]= array(
请注意,您在MySQL
按名称列进行排序,这样您的参赛作品就必须有序,前提是您有正确的COLLATION
:
正确的字符集/整理:
mysql> CREATE TABLE t ( f char(1)) charset=utf8;
Query OK, 0 rows affected (0.25 sec)
mysql> show full columns from t;
+-------+---------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-------+---------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| f | char(1) | utf8_general_ci | YES | | NULL | | select,insert,update,references | |
+-------+---------+-----------------+------+-----+---------+-------+---------------------------------+---------
mysql> INSERT INTO t VALUES ('a'),('p'),('ä'),('o'),('ñ'),('ò');
Query OK, 6 rows affected (0.09 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM t ORDER BY f;
+------+
| f |
+------+
| a |
| ä |
| ñ |
| o |
| ò |
| p |
+------+
6 rows in set (0.00 sec)
但错误的肆虐:
mysql> SELECT * FROM t ORDER BY CONVERT(f USING ascii);
+------+
| f |
+------+
| ä |
| ñ |
| ò |
| a |
| o |
| p |
+------+
6 rows in set (0.00 sec)