PHP 按字母顺序排列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4187498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:14:16  来源:igfitidea点击:

PHP Order in alphabetical order

phplist

提问by Alex Cane

I'm trying to make a simple alphabetical list to order items in my database. The thing I can't figure out is how to actually list it.

我正在尝试制作一个简单的按字母顺序排列的列表来对我的数据库中的项目进行排序。我无法弄清楚的是如何实际列出它。

I would like it to be the same format as you have on miniclip.com

我希望它与您在 miniclip.com 上的格式相同

Here's an image

这是一张图片

alt text

替代文字

I looked around, but couldnt find an answer really.

我环顾四周,但真的找不到答案。

(I would like it to finish even at the end of each vertical column, except the last one for sure)

(我希望它甚至在每个垂直列的末尾完成,当然除了最后一个)

Any help would be welcome!

欢迎任何帮助!

回答by Webnet

In MySQL:

在 MySQL 中:

SELECT * FROM table ORDER BY name ASC

In PHP:

在 PHP 中:

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

回答by jon_darkstar

He doesn't seem to have an issue with the storting, but doing the column format and headers for each new letter.

他似乎对存储没有问题,但为每个新字母做列格式和标题。

Suppose $arr contains your alphabetically sorted list with numeric keys. each element has indexes 'name' and 'link'. This should be pretty safe assumption for data from a SQL query.

假设 $arr 包含带有数字键的按字母顺序排序的列表。每个元素都有索引“名称”和“链接”。对于来自 SQL 查询的数据,这应该是非常安全的假设。

$firstLetter = -1;
$desiredColumns = 4;  //you can change this!
$columnCount = (count($arr)+27)/$desiredColumns+1;
echo "<table><tr><td>";
foreach($arr as $key => $cur)
{
    if ($key != 0 && $key % desiredColumns == 0) echo "</td><td>";
    if ($cur['name'][0] !== $firstLetter)
    {
        echo "<strong>$firstLetter</strong> <br />"; $firstLetter = $cur['name'][0];
    }
    echo "<a href=".$cur['link'].">".$cur['name']."</a><br />";
}
echo "</td><tr></table>";

You'll have to treat numbers as a special case, but this is the idea. If you are using a template engine there are obviously better ways of doing this, but I figure you would have mentioned that. This is a rough sketch, making pretty HTML isn't my thing.

您必须将数字视为一种特殊情况,但这就是想法。如果您使用的是模板引擎,显然有更好的方法可以做到这一点,但我想您会提到这一点。这是一个粗略的草图,制作漂亮的 HTML 不是我的事。

--Query-- get table into $arr.  I can't see your tables obviously, Im making assumptions if names nad stuff so you'll need to verify or change them

$sql = "SELECT * FROM table T ORDER BY name";
$conn = //you should have this
$res = mysql_query($sql, $conn);
$arr = array();
while($row = mysql_fetch_assc($res)
   $arr[] = $row;
// start above code here.  This isn't safe for empty query responses or other error but it works

回答by Gumbo

Assuming that your result set already is sorted by using the ORDER BYclause, to group the results by their first character you just need to remember the first character of the previous entry and print out the first character of the current entry if they are different. So:

假设您的结果集已经使用ORDER BY子句排序,要按第一个字符对结果进行分组,您只需要记住前一个条目的第一个字符,如果它们不同,则打印出当前条目的第一个字符。所以:

$prevLabel = null;
while ($row = mysql_fetch_assoc($result)) {
    $currLabel = strtoupper(substr($row['name'], 0, 1));
    if ($currLabel !== $prevLabel) {
        echo $currLabel;
        $prevLabel = $currLabel;
    }
    echo $row['name'];
}

This will print the first character as a label for each group that's members have the same first character.

这将打印第一个字符作为每个组成员具有相同第一个字符的标签。

回答by Jim K

I found this post and had the same problem. I used the code below to output a list by category name with a header equal to the first letter. In my database table (category) I have name and category_letter. So, name = football and category_list = 'F'.

我找到了这篇文章并遇到了同样的问题。我使用下面的代码按类别名称输出列表,标题等于第一个字母。在我的数据库表(类别)中,我有 name 和 category_letter。所以,name = Football 和 category_list = 'F'。

<section>
    <?php
    try {
        $cats_sql = $dbo->prepare("SELECT name, category_list, FROM category WHERE category_list REGEXP '^[A-Z#]' GROUP BY category_list ASC");
        $cats_sql->execute();
        $results_cats = $cats_sql->fetchAll();
    } catch(PDOException $e) {  
        include('basehttp/error');
    }   
    $array_cats = $results_cats;
    if(is_array($array_cats)) {
        foreach($array_cats as $row_cats) {
            $cat_var = $row_cats[category_list]; // Each Category list title
            ?>
            <aside>
            <h1><a name=""><? echo $cat_var ?></a></h1> 
            <?php
            try {
                $search_sql = $dbo->prepare("SELECT name, category_list FROM category WHERE category_list=:cat_var ORDER BY name ASC"); // Pulling a list of names for the category list
                $search_sql->bindParam(":cat_var",$cat_var,PDO::PARAM_STR);
                $search_sql->execute();
                $results_search = $search_sql->fetchAll();
            } catch(PDOException $e) {  
                include('basehttp/error');
            }   
            $array_search = $results_search;
            if(is_array($array_search)) { // Output list of names which match category
                foreach($array_search as $row_search) {
                    ?>
                    <h2><?php echo $row_search[name]; ?></h2>
                    <br class="clear">
                    <?php 
                }
            }
            ?>
            </aside>
            <br class="clear">
            <?php

        }
    }           
    ?>
</section>  

回答by James Thompson

There are two ways to do it.

有两种方法可以做到。

You could use your database and use the 'order' clause to pull them by a specific field alphabetically.

您可以使用您的数据库并使用“order”子句按字母顺序按特定字段提取它们。

You could also use either a key sort or value sort on a PHP array.

您还可以对 PHP 数组使用键排序或值排序。

The PHP functions are sort($array) and ksort($array).

PHP 函数是 sort($array) 和 ksort($array)。

http://php.net/manual/en/function.sort.php

http://php.net/manual/en/function.sort.php

http://php.net/manual/en/function.ksort.php

http://php.net/manual/en/function.ksort.php

<?php
  $list = $your_list_array_from_database
  //if you need info on how to do this, just let me know
  sort($list);

  foreach($list as $item) {
    echo $item;
  }
?>

回答by John Parker

I presume you're using MySQL (or another SQL) database, in which case you should simply retrieve the data in the required order using a SORT BY clause on the lookup SELECT. (Sorting this PHP is trivial via the sortfunction, but it makes sense to get the database to do this - that's pretty much what it's for.)

我假设您正在使用 MySQL(或其他 SQL)数据库,在这种情况下,您应该使用查找 SELECT 上的 SORT BY 子句以所需的顺序检索数据。(通过sort函数对此 PHP 进行排序是微不足道的,但让数据库执行此操作是有意义的 - 这几乎就是它的用途。)

In terms of balancing the output of each of the columns, you could get a COUNT of the required rows in your database (or simply use the count of the resulting PHP array of data) and use this to ensure that the output is balanced.

在平衡每一列的输出方面,您可以获得数据库中所需行的 COUNT(或仅使用生成的 PHP 数据数组的计数)并使用它来确保输出是平衡的。

As a final thought, if this is going to be output on a per-page basis, I'd highly recommend generating it into a static file when the structure changes and simply including this static file as a part of the output - generating this on the fly is needlessly resource inefficient.

最后,如果要在每页的基础上输出,我强烈建议在结构发生变化时将其生成到静态文件中,并简单地将此静态文件包含为输出的一部分 - 生成它苍蝇是不必要的资源效率低下。

回答by Alex C

The mysql option mentioned above is definitely the best bet. If the data comes out of the DM in order, that's the simplest way to go.

上面提到的 mysql 选项绝对是最好的选择。如果数据按顺序从 DM 出来,这是最简单的方法。

Your next option might be to look at the asort and ksort functions in PHP to find the exact one you're looking for.

您的下一个选择可能是查看 PHP 中的 asort 和 ksort 函数以找到您正在寻找的确切函数。

http://www.php.net/manual/en/array.sorting.php

http://www.php.net/manual/en/array.sorting.php

How are you pulling the data?

你是怎么拉数据的?

<?php
$result = mysql_query("SELECT titles FROM gamelist ORDER BY title ASC");
while ($row = mysql_fetch_assoc($result)) {
    echo "{$result['title']}<br/>";
}
?>

回答by Yogesh Naik

Its actually Simple....I did similar thing for my project once. I had to pull out all music albums name and categorize them in alphabetical order.

它实际上很简单......我曾经为我的项目做过类似的事情。我不得不提取所有音乐专辑名称并按字母顺序对它们进行分类。

In my table, "album_name" is the column where names are stored.

在我的表中,“album_name”是存储名称的列。

$sql= "select * from album_table order by album_name ASC";
$temp_char= ""; // temporary variable, initially blank;

using while loop, iterate through records;

使用while循环,遍历记录;

while($row= $rs->fetch_assoc())
{
$album_name= $row['album_name'];

$first_char_of_albm= $album_name[0]; // this will store first alphabet;

$first_char_of_albm= strtoupper($first_char_of_albm); // make uppercase or lower as per your needs 

if($temp_char!=$first_char_of_albm)
{
    echo $first_char_of_albm;

    $temp_char= $first_char_of_albm; // update $temp_char variable
}

}

That's it....

就是这样....

回答by Julian Soro

I am posting my answer to this old question for 3 reasons:

我发布我对这个老问题的回答有 3 个原因:

  1. You don't always get to write your queries to MySQL or another DBMS, as with a web service / API. None of the other answers address PHP sorting without query manipulation, while also addressing the vertical alphabetical sort
  2. Sometimes you have to deal with associative arrays, and only a couple other answers deal with assoc. arrays. BTW, my answer will work for both associative and indexed arrays.
  3. I didn't want an overly complex solution.
  1. 您并不总是像使用 Web 服务/API 那样将查询写入 MySQL 或其他 DBMS。其他答案都没有解决没有查询操作的 PHP 排序问题,同时也解决了垂直字母排序问题
  2. 有时您必须处理关联数组,而只有其他几个答案处理关联。数组。顺便说一句,我的答案适用于关联数组和索引数组。
  3. 我不想要一个过于复杂的解决方案。

Actually, the solution I came up with was pretty simple--use multiple tags with style="float:left", inside of a giant table. While I was sceptical that having multiple tbody tags in a single table would pass HTML validation, it in fact did pass without errors.

实际上,我想出的解决方案非常简单——在一个巨大的桌子内使用多个带有 style="float:left" 的标签。虽然我怀疑在一个表中包含多个 tbody 标签是否会通过 HTML 验证,但实际上它确实通过而没有错误。

Some things to note:

一些注意事项:

  • $numColsis your desired number of columns.
  • Since we are floating items, you may need to set the width and min-width of parent elements and/or add some <br style="clear: both" />, based on your situation.
  • for alternative sorting methods, see http://php.net/manual/en/array.sorting.php
  • $numCols是您想要的列数。
  • 由于我们是浮动项目,您可能需要根据您的情况设置父元素的宽度和最小宽度和/或添加一些 <br style="clear: both" />。
  • 有关其他排序方法,请参阅http://php.net/manual/en/array.sorting.php

Here's my full answer:

这是我的完整答案:

function sortVertically( $data = array() )
{
    /* PREPARE data for printing */
    ksort( $data );     // Sort array by key.
    $numCols    = 4;    // Desired number of columns
    $numCells   = is_array($data) ? count($data) : 1 ;
    $numRows    = ceil($numCells / $numCols);
    $extraCells = $numCells % $numCols;  // Store num of tbody's with extra cell
    $i          = 0;    // iterator
    $cCell      = 0;    // num of Cells printed
    $output     = NULL; // initialize 


    /* START table printing */
    $output     .= '<div>';
    $output     .= '<table>';

    foreach( $data as $key => $value )
    {
        if( $i % $numRows === 0 )   // Start a new tbody
        {
            if( $i !== 0 )          // Close prev tbody
            {
                $extraCells--;
                if ($extraCells === 0 )
                {
                    $numRows--;     // No more tbody's with an extra cell
                    $extraCells--;  // Avoid re-reducing numRows
                }
                $output .= '</tbody>';
            }

            $output .= '<tbody style="float: left;">';
            $i = 0;                 // Reset iterator to 0
        }
        $output .= '<tr>';
            $output .= '<th>'.$key.'</th>';
            $output .= '<td>'.$value.'</td>';
        $output .= '</tr>';

        $cCell++;                   // increase cells printed count
        if($cCell == $numCells){    // last cell, close tbody
            $output .= '</tbody>';
        }

        $i++;
    }

    $output .= '</table>';
    $output .= '</div>';
    return $output;
}

I hope that this code will be useful to you all.

我希望这段代码对大家有用。