Repeating rows in an array and them paginating them
Lets say I have a table with 20 rows and a pagination script.
The pagination script is set to display 10 rows per page and of course it will display two pages.
The problem is that sometimes my table will have less than 20 rows, lets say 3 - so the script will display just one page with 3 entries.
I need a way to reppeat those 3 rows untill the number reachers 20, store them in an array, and than use the pagination script as normal.
Any ideeas, can it be done? Can someone put this in a code?
For those who wonder why?:) This is a problem becouse with each row i have asigned a post from my blog, and I have 20 posts which i want displayed. If for example the table which aoutoupdates with cron jobs has 17 rows, i'll have just 17 posts asociated with them. This is why i need to repreat them until 20, 开发者_如何学Cso i'll have all my 20 posts displayed no matter how many rows i have in the table:)
$query = "SELECT * FROM `db_table`";//PUT HERE A PROPER QUERY.
$result = mysql_result($query);
// mysql_num_rows($result) >10 WE ARE CHECKING HOW MANY LINES DO WE HAVE.
if(mysql_num_rows($result) >10){
/*...YOUR EXISTING CODES HERE...*/
}
else{
while($rows = mysql_fetch_assoc($result)){
$arrayOfRows[] = $rows; // HERE WE PULL ROWS FROM DB AND PUT IN AN ARRAY.
}
}
// NOW YOUR DB ROWS ARE IN THE ARRAY NAMED $arrayOfRows IF YOUR DB TABLE HAS LESS THEN 10 ROWS
$countRowsOfArray = count($arrayOfRows);
$rows = 20;
$dbRow=0;
for($n=0;$n<$rows;$n++){
if($dbRow > $countRowsOfArray) $dbRow = 0;
$newArrayOfRows[$n] = $arrayOfRows[$dbRow];
$dbRow++;
}
//NOW YOU HAVE $newArrayOfRows WHICH YOUR ROWS REPEATED UNTIL 20 LINES.
print_r($newArrayOfRows); //SEE IF THEY ARE THERE.
A simple solution would be (note: this code is optimized for readability, not speed):
$result = array();
for($i = 0; $i < 20; $i++){
$result = $array[$i % sizeof($array)];
}
This will fill the $result array with the contents of $array, repeating if necessary. You can also replace the loop condition by:
$i < 20 || $i < sizeof($array)
This will copy the whole array and, if necessary (the array has less than 20 entries), add copies.
精彩评论