PHP order in alphabetical order

I am trying to create a simple alphabetical list for ordering items in my database. I can’t figure out how to do this.

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

Here is the image

alt text

I looked around, but could not find the answer.

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

Any help would be appreciated!

+4
source share
9 answers

In MySQL:

SELECT * FROM table ORDER BY name ASC 

In 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 
+5
source

It doesn't seem to have a problem with sorting, but it does column format and headings for each new letter.

Suppose $ arr contains your alphabetically sorted list with number keys. each element has index names' and 'link'. This should be a pretty safe guess for the data from the SQL query.

 $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 will have to treat the numbers as a special case, but this is an idea. If you use the template engine, obviously this is better, but I think you would mention it. This is a rough sketch, which makes pretty HTML not my thing.

 --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 
+2
source

There are two ways to do this.

You can use your database and use the "order" clause to pull them by a specific field in alphabetical order.

You can also use sorting or sorting keys in a PHP array.

PHP functions are sorting ($ array) and ksort ($ array).

http://php.net/manual/en/function.sort.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; } ?> 
+1
source

I assume that you are using a MySQL database (or another SQL), in which case you just need to get the data in the required order using the SORT BY clause in a SELECT search. (Sorting this PHP is trivial with the sort function, but it makes sense to get the database to do this - this is pretty much what it is for.)

In terms of balancing the output of each of the columns, you can get COUNT from the required rows in your database (or just use the counter of the resulting PHP data array) and use this to ensure that the result is balanced.

As a final thought, if this is to be displayed on the basis of each page, I would strongly recommend creating it in a static file when the structure changes and simply includes this static file as part of the output - generating this on the fly is uselessly inefficient.

+1
source

The mysql option mentioned above is definitely the best choice. If the data comes from the DM in order, this is the easiest way to go.

The next option would be to look at asort and ksort in PHP to find what you are looking for.

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

How do you retrieve data?

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

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

 $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 whose members have the same first character.

+1
source

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

 <section> <?php try { $cats_sql = $dbo->prepare("SELECT name, category_list, FROM category WHERE category_list REGEXP '^[AZ#]' 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> 
+1
source

Actually it's just .... I did a similar thing for my project once. I had to pull out all the names of the music albums and classify them in alphabetical order.

In my table, the album name is the column where the names are stored.

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

using a while loop, iterating over the records;

 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 } } 

What is it....

+1
source

I post my answer to this old question for three reasons:

  • You cannot always write your queries in MySQL or another DBMS, as in a web service / API. None of the other answers respond to PHP sorting without query manipulation, or to vertical sorting alphabetically.
  • Sometimes you have to deal with associative arrays, and only a couple of other answers are associated with the association. arrays. BTW, my answer will work for both associative and indexed arrays.
  • I didn’t want a solution that was too complicated.

In fact, the solution I came up with was pretty simple - use a few tags with style = "float: left" inside a giant table. Although I was skeptical that having multiple tag tags in the same table would pass HTML validation, it actually passed without errors.

Some notes:

  • $ numCols is the required number of columns.
  • Since we are floating elements, you may need to set the width and minimum width of the parent elements and / or add some <br style = "clear: both" /> character, based on your situation.
  • for alternative sorting methods, see http://php.net/manual/en/array.sorting.php

Here is my complete 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 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 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 this code will be useful to all of you.

0
source

All Articles