PHP Order in alphabetical order - php

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
Here's an image
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!

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

Assuming that your result set already is sorted by using the ORDER BY clause, 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:
$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.

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.
$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 "".$cur['name']."<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.
--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

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 sort function, but it makes sense to get the database to do this - that's pretty much what it's for.)
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.
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.

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.
Your next option might be to look at the
asort and ksort functions in PHP to find the exact one you're looking for.
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/>";
}
?>

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.
You could also use either a key sort or value sort on a PHP array.
The PHP functions are sort($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;
}
?>

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'.
<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>

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.
$sql= "select * from album_table order by album_name ASC";
$temp_char= ""; // temporary variable, initially blank;
using while loop, iterate through 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
}
}
That's it....

I am posting my answer to this old question for 3 reasons:
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
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.
I didn't want an overly complex solution.
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.
Some things to note:
$numCols is 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
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.

Related

How can I store large chunks into json file without memory crash?

I have an array $table and it contains 6000 items.
When I want to convert this array to json and store it into a file, my memory crashes.
So I had the idea to break the array into chunks of parts with 500 items:
$table = array_chunk($table, 500);
$table_json = $serializer->serialize($table[0], 'json', $context);
$myfile = fopen($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", "w") or die("Unable to open file!");
file_put_contents($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", $table_json);
This runs fast now, but of course now only 500 items are stored. Is there a way to add the other parts of the $table array without memory crash?
You could do something like this as you mentioned you know how to use array_chunk();
Let's look into simplifying the process with a built-in PHP function called array_chunk();
We'll be using HTML tables for design which isn't recommended. The task is better accomplished with CSS, you can follow same way without HTML and CSS.
Our table :
id datePosted firstName lastName pictureName anotherColumn
1 2013-07-01 John Smith SmithJohn.jpg anotherValue
2 2013-05-06 Elroy Johnson JohnsonElroy.jpg anotherValue
3 2013-06-18 Jake Bible BibleJake.jpg anotherValue
4 2013-07-17 Steve Stevenson StevensonSteve.jpg anotherValue
5 2013-04-08 Bill Smith SmithBill2.jpg anotherValue
Building HTML Tables
PDO query is used to grab the database information with prepared statements, Note that the loop only generates the code to display the columns.
The tests to detect where the rows begin and end are unnecessary.
//INITIALIZE VARIABLES
$colsToDisplay = 3;
$htmlOutput = array();
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$htmlOutput[] = "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
}
Once the loop is done, the array containing the column information can be broken into groups of three... or whatever value was assigned to $colsToDisplay, What we did here ? we tooks 3 columns from table, So divide table in two parts.
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//...
}
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);
All that's left is to display the table information. Note that array_chunk() creates a multi-dimensional array. The foreach loop is used to process the groups of columns. Each group is assigned to $currRow which contains an array of columns for the current row. The implode() function is used to quickly display the columns as a string.
Lets continue :
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);
//DISPLAY TABLE
print '<table>';
foreach($htmlOutput as $currRow) {
print '<tr>' . implode('', $currRow) . '</tr>';
}
print '</table>';
Checking For Missing Column Tags
One thing you may have noticed is the code to add missing columns was left out.
In other words, this example results in an HTML table where the last row only has two columns.
Apparently, the missing columns aren't needed according to the W3C Markup Validation Service… so they weren't included. However, they can be added by running the following code right before array_chunk() is called.
$colsDifference = count($htmlOutput) % $colsToDisplay;
if($colsDifference) {
while($colsDifference < $colsToDisplay) {
$htmlOutput[] = '<td></td>';
$colsDifference++;
}
}
Final Code :
//INITIALIZE VARIABLES
$colsToDisplay = 3;
$htmlOutput = array();
//GET PICTURE LIST
$sql = "SELECT datePosted, firstName, lastName, pictureName FROM pictureList ORDER BY datePosted DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$htmlOutput[] = "<td><img src='images/{$row['pictureName']}' alt='' /><br />{$row['firstName']} {$row['lastName']}</td>";
}
//OPTIONAL CODE
//IF NEEDED, ADD MISSING COLUMNS
$colsDifference = count($htmlOutput) % $colsToDisplay;
if($colsDifference) {
while($colsDifference < $colsToDisplay) {
$htmlOutput[] = '<td></td>';
$colsDifference++;
}
}
//END: OPTIONAL CODE
//BREAK THE COLUMNS INTO GROUPS
$htmlOutput = array_chunk($htmlOutput, $colsToDisplay);
//DISPLAY TABLE print '<table>';
foreach($htmlOutput as $currRow) {
print '<tr>' . implode('', $currRow) . '</tr>';
}
print '</table>';
Idea Behind This Tutorial :
You dont need to create a file and write arrays into that file to display in datatable.
If you still wants that you can (divide table in two parts) to create two arrays and than write into file, and than use array_push(); or array_merge(); to get both arrays into one.
I might have bad explanition please forgive for mistakes, Hope this help you in your coding life :)
Sticking to your solution, you can append the other chunks to your exisiting file. This works by setting the flag FILE_APPEND, e.g.:
$table_json = $serializer->serialize($table[1], 'json', $context);
$myfile = fopen($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", "w") or die("Unable to
open file!");
file_put_contents($_SERVER['DOCUMENT_ROOT']."/files/myfile.json", $table_json, FILE_APPEND | LOCK_EX);
(LOCK_EX flag to prevent anyone else writing to the file at the same time)

Storing mysql result in array (without echoing) and then using that array to set another variable

I've tried looking for a solution in other questions asked before (as always), but I can't seem to wrap my head around this.
See, I want to get a number of unique IDs (in random order) from one table and store them in an array without echoing them. Then I want to use that array variable in a loop, so that I can increment the key with every pass, and set another variable to that array variable. Confusing? I think looking at the code will make it more clear.
The problem is I can't seem to store the values that I've queried into an array for later use in the code. I pasted the pertinent part of the code with my spots of trouble indicated by comment /* */ tags.
Any help is appreciated.
<?php
include ('parse_functions.php');
if ($fetch['use_rand']=='yes')
{ $loop = 5;
$concept = $fetch['concept'];
$countRandom = "SELECT exID FROM examples WHERE concept='$concept' ORDER BY RAND()";
$askForRandom = mysql_query($countRandom) or die(mysql_error());
/* HERE I NEED TO STORE RANDOM KEYS (exID) INTO AN ARRAY */ }
else
{ if (!empty($fetch['ex5'])) { $loop = 5; }
elseif (!empty($fetch['ex4'])) { $loop = 4; }
elseif (!empty($fetch['ex3'])) { $loop = 3; }
elseif (!empty($fetch['ex2'])) { $loop = 2; }
elseif (!empty($fetch['ex1'])) { $loop = 1; }
else { $loop = 0; }
}
if ($loop!==0)
{
echo '<div id="examples">' . "\n";
echo '<table class="showExample" cellspacing="0" cellpadding="0" border="0" align="center">' . "\n";
$turns = 1;
do {
if ($fetch['use_rand']=='no')
{ $exID = $fetch['ex'.$turns.'']; }
else
{ $exID = /* THIS IS WHERE I WILL USE "RANDOM VARIABLE" */; }
$askExamples = "SELECT * FROM examples WHERE exID='$exID'";
$getExamples = mysql_query($askExamples) or die(mysql_error());
$sortExamples = mysql_fetch_assoc($getExamples);
echo '<tr>' . "\n";
// ...and so on
If all you need to do is store the info in an array, here's an easy way about it.
/* code
to open
db here
*/
/* assuming you have a value for $concept */
$countRandom = "SELECT exID FROM examples WHERE concept='$concept' ORDER BY RAND()";
$askForRandom = mysql_query($countRandom) or die(mysql_error());
$Element = 0; //Array elements start at ZERO. So this is to intialise it.
while ($Fields = mysql_fetch_array($askforRandom)) //As long as there are records, get them.
{
//Records are retrieved one at a time. So store each one's exID in the array element
$Data[$Element] = $Fields["exID"];
//Soon after storing one, increment the value of the $Element variable so it is ready for the next one.
$Element++
}
/* now you have the data in the array. So you can do what you like with it. */
hope it helps
NOTE: when reading the array, make sure you put the condition to check that your counter is LESS than $Element. This is because after reading the last record, $Element is incremented by one. Hope this is clear.
Why not just grab all the right information in one query from the start along the lines of something like this:
select
a.exID,
examples.someField,
examples.someOtherField
from
examples
join
(
SELECT
exID
FROM
examples
WHERE
concept='$concept'
ORDER BY
RAND()
limit 5
) a
on a.exID=examples.exID
Then you just just pop them into an array (or better yet object) that has all the pertinent information in one row each time.

How can I copy a database table to an array while accounting for skipped IDs?

I previously designed the website I'm working on so that I'd just query the database for the information I needed per-page, but after implementing a feature that required every cell from every table on every page (oh boy), I realized for optimization purposes I should combine it into a single large database query and throw each table into an array, thus cutting down on SQL calls.
The problem comes in where I want this array to include skipped IDs (primary key) in the database. I'll try and avoid having missing rows/IDs of course, but I won't be managing this data and I want the system to be smart enough to account for any problems like this.
My method starts off simple enough:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Two notes:
Yes, I should probably move that $localityMax check to a PHP loop.
I'm intentionally skipping the first array key.
The problem here is that any missed key in the database isn't accounted for, so it ends up outputting like this (sample table):
1 - Tok
2 - Juneau
3 - Anchorage
4 - Nashville
7 - Chattanooga
8 - Memphis
-
-
I want to write "Error" or NULL or something when the row isn't found, then continue on without interrupting things. I've found I can check if $i is less than $row[$i] to see if the row was skipped, but I'm not sure how to correct it at that point.
I can provide more information or a sample database dump if needed. I've just been stuck on this problem for hours and hours, nothing I've tried is working. I would really appreciate your assistance, and general feedback if I'm making any terrible mistakes. Thank you!
Edit: I've solved it! First, iterate through the array to set a NULL value or "Error" message. Then, in the assignations, set $i to $row["id"] right after the mysql_fetch_assoc() call. The full code looks like this:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Reset
for ($i=1;$i<$localityMax+1;$i++)
{
$localityData["id"][$i] = NULL;
$localityData["name"][$i] = "Error";
}
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$i = $row["id"];
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Thanks for the help all!
Primary keys must be unique in MySQL, so you would get a maximum of one possible blank ID since MySQL would not allow duplicate data to be inserted.
If you were working with a column that is not a primary or unique key, your query would need to be the only thing that would change:
SELECT id, name FROM localities WHERE id != "";
or
SELECT id, name FROM localities WHERE NOT ISNULL(id);
EDIT: Created a new answer based on clarification from OP.
If you have a numeric sequence that you want to keep unbroken, and there may be missing rows from the database table, you can use the following (simple) code to give you what you need. Using the same method, your $i = ... could actually be set to the first ID in the sequence from the DB if you don't want to start at ID: 1.
$result = mysql_query('SELECT id, name FROM localities ORDER BY id');
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[(int) $row['id']] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
// This saves a query to the database and a second for loop.
end($data); // move the internal pointer to the end of the array
$max = key($data); // fetch the key of the item the internal pointer is set to
for ($i = 1; $i < $max + 1; $i++) {
if (!isset($data[$i])) {
$data[$i] = array(
'id' => NULL,
'name' => 'Erorr: Missing',
);
}
echo "$i. {$data[$id]['id']} - {$data[$id]['name']}<br />\n";
}
After you've gotten your $localityResult, you could put all of the id's in an array, then before you echo $localityDataStuff, check to see
if(in_array($i, $your_locality_id_array)) {
// do your echoing
} else {
// echo your not found message
}
To make $your_locality_id_array:
$locality_id_array = array();
foreach($localityResult as $locality) {
$locality_id_array[] = $locality['id'];
}

PHP - Nested List Broken into Even Columns (fix and updates)

I have a follow-up to a previous thread/question that I hope can be solved by relatively small updates to this existing code. In the other thread/question, I pretty much solved a need for a nested unordered list. I needed the nested unordered list to be broken up into columns based on the number of topics.
For example, if a database query resulted in 6 topics and a user specified 2 columns for the layout, each column would have 3 topics (and the related news items below it).
For example, if a database query resulted in 24 topics and a user specified 4 columns for the layout, each column would have 6 topics (and the related news items below it).
The previous question is called PHP - Simple Nested Unordered List (UL) Array.
The provided solution works pretty well, but it doesn't always divide
correctly. For example, when $columns = 4, it only divides the
columns into 3 groups. The code is below.
Another issue that I'd like to solve was brought to my attention by
the gentleman who answered the question. Rather than putting
everything into memory, and then iterating a second time to print it
out, I would like to run two queries: one to find the number of
unique TopicNames and one to find the number of total items in the
list.
One last thing I'd like to solve is to have a duplicate set of
code with an update that breaks the nested unordered list into columns
based on the number of news items (rather than categories). So, this
would probably involve just swapping a few variables for this second
set of code.
So, I was hoping to solve three issues:
1.) Fix the division problem when relying on the number of categories (unordered list broken up into columns based on number of topics)
2.) Reshape the PHP code to run two queries: one to find the number of unique TopicNames and one to find the number of total items in the list
3.) Create a duplicate set of PHP code that works to rely on the number of news items rather than the categories (unordered list broken up into columns based on number of news items)
Could anyone provide an update or point me in the right direction? Much appreciated!
$columns = // user specified;
$result = mysql_query("SELECT * FROM News");
$num_articles = 0;
// $dataset will contain array( 'Topic1' => array('News 1', 'News2'), ... )
$dataset = array();
while($row = mysql_fetch_array($result)) {
if (!$row['TopicID']) {
$row['TopicName'] = 'Sort Me';
}
$dataset[$row['TopicName']][] = $row['NewsID'];
$num_articles++;
}
$num_topics = count($dataset);
// naive topics to column allocation
$topics_per_column = ceil($num_topics / $columns);
$i = 0; // keeps track of number of topics printed
$c = 1; // keeps track of columns printed
foreach($dataset as $topic => $items){
if($i % $topics_per_columnn == 0){
if($i > 0){
echo '</ul></div>';
}
echo '<div class="Columns' . $columns . 'Group' . $c . '"><ul>';
$c++;
}
echo '<li>' . $topic . '</li>';
// this lists the articles under this topic
echo '<ul>';
foreach($items as $article){
echo '<li>' . $article . '</li>';
}
echo '</ul>';
$i++;
}
if($i > 0){
// saw at least one topic, need to close the list.
echo '</ul></div>';
}
UPDATE 12/19/2011: Separating Data Handling from Output Logic (for the "The X topics per column variant"):
Hi Hakre: I've sketched out the structure of my output, but am struggling with weaving the two new functions with the old data handling. Should the code below work?
/* Data Handling */
$columns = // user specified;
$result = mysql_query("SELECT * FROM News LEFT JOIN Topics on Topics.TopicID = New.FK_TopicID WHERE News.FK_UserID = $_SESSION[user_id] ORDER BY TopicSort, TopicName ASC, TopicSort, NewsTitle");
$num_articles = 0;
// $dataset will contain array( 'Topic1' => array('News 1', 'News2'), ... )
$dataset = array();
while($row = mysql_fetch_array($result)) {
if (!$row['TopicID']) {
$row['TopicName'] = 'Sort Me';
}
$dataset[$row['TopicName']][] = $row['NewsID'];
$num_articles++;
}
/* Output Logic */
function render_list($title, array $entries)
{
echo '<ul><li>', $title, '<ul>';
foreach($entries as $entry)
{
echo '<li>', $entry['NewsID'], '</li>';
}
echo '</ul></li></ul>;
}
function render_column(array $topics)
{
echo '<div class="column">';
foreach($topics as $topic)
{
render_list($topic['title'], $topic['entries']);
}
echo '</div>';
}
You have not shown in your both questions what the database table is, so I can not specifically answer it, but will outline my suggestion.
You can make use of aggregation functions in mysql to obtain your news entries ordered and grouped by topics incl. their count. You can do two queries to obtain counts first, that depends a bit how you'd like to deal with your data.
In any case, using the mysql_... functions, all data you selected from the database will be in memory (even twice due to internals). So having another array as in your previous question should not hurt much thanks to copy on write optimization in PHP. Only a small overhead effectively.
Next to that before you take care of the actual output, you should get your data in order so that you don't need to mix data handling and output logic. Mixing does make things more complicated hence harder to solve. For example if you put your output into simple functions, this gets more easy:
function render_list($title, array $entries)
{
echo '<ul><li>', $title, '<ul>';
foreach($entries as $entry)
{
echo '<li>', $entry['NewsID'], '</li>';
}
echo '</ul></li></ul>;
}
function render_column(array $topics)
{
echo '<div class="column">';
foreach($topics as $topic)
{
render_list($topic['title'], $topic['entries']);
}
echo '</div>';
}
This already solves your output problem, so we don't need to care about it any longer. We just need to care about what to feed into these functions as parameters.
The X topics per column variant:
With this variant the data should be an array with one topic per value, like you did with the previous question. I would say it's already solved. Don't know which concrete problem you have with the number of columns, the calculation looks good, so I skip that until you provide concrete information about it. "Does not work" does not qualify.
The X news items per column variant:
This is more interesting. An easy move here is to continue the previous topic with the next column by adding the topic title again. Something like:
Topic A Topic A Topic B
- A-1 - A-5 - B-4
- A-2 Topic B - B-5
- A-3 - B-1 - B-6
- A-4 - B-2
- B-3
To achieve this you need to process your data a bit differently, namely by item (news) count.
Let's say you managed to retrieve the data grouped (and therefore sorted) from your database:
SELECT TopicName, NewsID FROM news GROUP BY 1;
You can then just iterate over all returned rows and create your columns, finally output them (already solved):
$itemsPerColumn = 4;
// get columns
$topics = array();
$items = 0;
$lastTopic = NULL;
foreach ($rows as $row)
{
if ($lastTopic != $row['TopicName'])
{
$topic = array('title' => $row['TopicName']);
$topics[] = &$topic;
}
$topic['entries'][] = $row;
$items++;
if ($items === $itemsPerColumn)
{
$columns[] = $topics;
$topics = array();
$lastTopic = NULL;
}
}
// output
foreach($columns as $column)
{
render_column($column);
}
So this is actually comparable to the previous answer, but this time you don't need to re-arrange the array to obtain the news ordered by their topic because the database query does this already (you could do that for the previous answer as well).
Then again it's the same: Iteration over the returned result-set and bringing the data into a structure that you can output. Input, Processing, Output. It's always the same.
Hope this is helpful.

Adding commas to a loop within a loop

I'm trying to create a list using a loop within a loop. I have 3 tables.
T1: faculty
T2: keywords
T3: facID, keywordID
I've created a select statement to cross join the rows and spit out something like this:
Faculty Name A
keyword-a keyword-b keyword-c
Faculty Name B
keyword-a keyword-d keyword-f
Everything works great except I need to add commas to the keyword list and my code isn't doing the trick. My keywords are still looping through without the comma.
<?php while ($row = mysql_fetch_assoc($result)) { ?>
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
<?php $kwords = array();
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
echo implode(', ', $kwords);
} ?>
Any suggestions? I'm a noob and I'm hoping it's something very obvious!
There seem to be a few issues with your code, so I'll try to address them all.
First, you have a lot of opening and closing <?php> tags, and it's really messing with the readability of your code. Consider keeping as much code as possible contained into a single <?php> code block. For example, instead of this:
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
...you can consolidate all of that PHP code into this:
<?php
if ($row['facID'] !== $lastID ) {
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
?>
Next, you're not outputting any sort of visual break after echoing out your implode()ed array. This would lead to the next heading being output on the same line as the output of your previous heading. For example, your first two headings will end up like this:
Faculty Name A
keyword-a keyword-b keyword-cFaculty Name B
keyword-a keyword-d keyword-f
Notice how Faculty Name B is at the end of the line of keywords?
Finally, I think the problem you're reporting is that you're getting two keywords that are linked together. For example, if you had two rows of data with the same facility id, one with keywords keyword-a and keyword-b and another with keyword-c and keyword-d, you would see that output visually without a comma between keyword-b and keyword-c.
In other words, instead of this:
keyword-a, keyword-b, keyword-c, keyword-d
...you're instead seeing this:
keyword-a, keyword-bkeyword-c, keyword-d
This is also caused by the lack of a visual break between implodeed lines, but I believe the problem is deeper than that. I believe you want all keywords for a given facility to be shown on a single line, not broken across multiple lines. For that, you need to move where you reinitialize your array so that it gets reinitialized at the same time you switch to a new heading. Try something like this:
$kwords = array();
while ($row = mysql_fetch_assoc($result)) {
if ($row['facID'] !== $lastID ) {
if ($kwords) {
echo implode(", ", $kwords) . "<br />";
$kwords = array();
}
echo $row['facname'] . "<br />";
$lastID = $row['facID'];
}
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
}
if ($kwords) {
echo implode(", ", $kwords);
}
echo "<br />";
This still isn't the best code, but you can refactor it.
The idea here is that the array gets output and reset every time the facility changes, so that the array encompasses all keywords for that facility and they all get output together, rather than being reported only as part of the database row they were returned with. After the loop completes, you have to manually report the last row since the usual reporting is taken care of within the loop.

Categories