我在mySQL表中存储了这些类型的带有字母的数字
1 2a 2b 2c 3a 3b 4 5a 5b 10
有些有字母,有些没有。
对于上面的示例数据,我希望它像这样在页面上显示1
2a / 2b / 2c
3a / 3b
4
5a / 5b
10
这是我所拥有的基本内容所以你可以以此为基础在页面下方列出它们
$sql = mysql_query("SELECT * FROM data") or die(mysql_error());
while($row = mysql_fetch_assoc($sql))
{
$dataID = $row['dataID'];
echo $dataID . "<br />";
}
我可能可以用一些子字符串和if语句来做到这一点,但我有一种感觉,它可以用更好的方式来完成…可能使用正则表达式
看看natsort()函数。
这个函数实现了按字母数字排序的排序算法以人类的方式保存字符串,同时保持键/值关联。这被描述为"自然排序"。
这里的一个家伙帮了我,给了我这段很好的代码。我的把戏刚刚好。
$query = "select dataID, dataID * 1 as ord FROM data order by ord, dataID";
$result = mysql_query($query);
$heading = null; // remember last heading, initialize to a value that will never exist as data
while(list($dataID,$ord) = mysql_fetch_row($result)){
if($heading != $ord){
// a new (or first) heading found
if($heading != null){
// not the first heading, close out the previous section
echo implode (' / ',$data) . '<br />';
}
$heading = $ord; // remember new heading
// start a new section
$data = array();
}
// handle each piece of data
$data[] = $dataID;
}
// close out the last section
echo implode (' / ',$data) . '<br />';