简体   繁体   English

PHP或MySQL-如何仅显示同一值的多个表行

[英]PHP or MySQL - how to display only one table row out of many with the same value

I wrote this simple code which outputs first letters of values (in this case names of companies) stored in every each table row: 我写了这个简单的代码,它输出存储在每个表行中的值的首字母(在这种情况下为公司名称):

include_once('db.php'); //connection with database

$result = mysql_query("SELECT distinct Name FROM companies ORDER BY Name");

while ($row = mysql_fetch_array($result)) {
$letter = substr($row[0], 0, 1);     
echo '<p><a href="#">' . $letter . '</a>/p>';
} 

The companies table contains names of companies and the $letter variable contains first letter of those names. companies表包含公司名称,而$letter变量包含这些名称的首字母。

Apparently in the companies table there are many names starting with the same letter. 显然,在公司表中,有许多以相同字母开头的名称。

Now, how to display only one letter "A", one letter "B", one letter "C" etc. out of many letters "A", "B", "C" etc.? 现在,如何在许多字母“ A”,“ B”,“ C”等中仅显示一个字母“ A”,一个字母“ B”,一个字母“ C”等?

Why don't you put that in your query itself? 您为什么不将其放入查询本身?

Modify the query to 修改查询为

SELECT distinct SUBSTRING(Name,1,1) FROM company ORDER BY SUBSTRING(Name,1,1)

Here's the sql fiddle 这是SQL小提琴

To do this in PHP you can create a blank array and push the first letter of each company onto the array if it doesnt already exist like this: 要在PHP中执行此操作,您可以创建一个空白数组,并将每个公司的首字母推入该数组(如果尚不存在),如下所示:

include_once('db.php'); //connection with database

$result = mysql_query("SELECT distinct Name FROM companies ORDER BY Name");

$letters = array();

while ($row = mysql_fetch_array($result)) {
    if(!in_array(substr($row[0], 0, 1), $letters)){
        array_push($letters, substr($row[0], 0, 1));
    }    
} 

foreach($letters as $l){
    echo '<p><a href="#">' . $l . '</a></p>';
}

If you want to show all letters of the alphabet even if a company doesnt start with that letter you can use the PHP range function like this: 如果即使一家公司并非以该字母开头,也要显示所有字母,那么可以使用如下所示的PHP range函数:

foreach (range('a', 'z') as $letter) {
    echo '<p><a href="#">' . $letter . '</a></p>';
}

Use this SQL statement 使用此SQL语句

SELECT DISTINCT SUBSTR(Name,1,1) FROM companies ORDER BY Name;

This will return distinct values from first letter of Names; 这将返回名称的首字母不同的值;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM