Spanning all data across 3 lists

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
josephman1988
Forum Newbie
Posts: 15
Joined: Mon Apr 21, 2008 8:29 am

Spanning all data across 3 lists

Post by josephman1988 »

Guys, I have a slight problem.

Ok so I have a table (LEFT) joined:

Code: Select all

SELECT news.n_id, news.n_title, news.n_date, games.g_title, news.g_id 
FROM games 
LEFT JOIN news 
ON games.g_id = news.g_id
ORDER BY news.g_id
n_id = the news id
n_title = the news title
g_title = game category title
g_id = game category id

What I want is to get all the data in the news table and count how many rows of data their are:

Code: Select all

$selectnews = mysql_query("SELECT * FROM news");
 
$num_rows = mysql_num_rows($selectnews);
Now what I am having problem with is, I want to span the news over 3 lists alongside each other like so:
| 1/3 of the data | 2nd 1/3 of the data | last of the 1/3 of the data |

How would I go about doing this?

Regards,
Joe.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Spanning all data across 3 lists

Post by requinix »

Buffer all the data into an array, figure out how many there are and so many rows there will be in the first couple columns (first and second column have the same number, third column has the same minus 0, 1, or 2).

If there are $row rows, have a for loop from 0 to $row-1. Inside, print item X, $row+X, and 2*$row+X - make sure that 2*$row+X isn't past the end of the buffered data.

Code: Select all

<pre><?php
 
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
 
$count = count($data);
$rows = ceil($count / 3);
for ($i = 0; $i < $rows; $i++) {
    echo $data[$i], "\t", $data[$rows+$i], "\t";
    if (2*$rows+$i < $count) echo $data[2*$rows+$i];
    echo "\n";
}
?></pre>
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Spanning all data across 3 lists

Post by John Cartwright »

Code: Select all

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
 
$chunks = array_chunk($data, ceil(count($data) / 3));
 
 
Will split your array into 3 chunks, which can then be displayed much more easily than looping logic.
Post Reply