I have a simple news system that i need to change so i can limit the items per page but i don't have anything that would do this, so i need to do this myself.
Basically the function just displays the whole array of the flat files and i would like to limit it to 3 items per page(configurable).
My starting logic was:
$itemspage=pages->current_page;
$itemsperpage=3;
$limitn=$itemperpage*$itemspage;
$itemindex=$limitn-2;
if page was 1 it would display the news from array index 1,2,3 if page was 2 it would display the news from array index 4,5,6 and so on...
i think this logically should work but what if the news in the array can't be split into 3? with this logic this should (at least on the starting index) cause a bug.
The whole code is here:
$list = $this->getNewsList();
$pages = new Paginator;
echo "<table class='newsList'>";
foreach ($list as $value) {
$newsData = file($this->newsDir.DIRECTORY_SEPARATOR.$value);
$newsTitle = $newsData[0];
$submitDate = $newsData[1];
unset ($newsData['0']);
unset ($newsData['1']);
$newsContent = "";
$itemspage=pages->current_page;
$itemperpage=3;
$limitn=$itemperpage*$itemspage;
$itemindex=$limitn - 2;
foreach ($newsData as $value) {
$newsContent .= $value;
}
echo "<tr><th align='left'>$newsTitle</th>
<th class='right'>$submitDate</th></tr>";
echo "<tr><td colspan='2'>".$newsContent."<br/></td></tr>";
}
echo "</table>";
The for hasn't been done yet only the logic behind the split. Could you help me?
I'm not sure how you're building your $newsContent, but maybe your answer is in here:
$list = $this->getNewsList();
$pages = new Paginator;
$itemspage = $pages->current_page;
$itemperpage = 3; // you might want te define this property in the paginator also ($itemperpage = $pages->items_per_page);
$currentPageList = array_slice($list, ($itemspage - 1) * $itemperpage, $itemspage);
echo "<table class='newsList'>";
foreach ($currentPageList as $value) {
$newsData = file($this->newsDir.DIRECTORY_SEPARATOR.$value);
$newsTitle = $newsData[0];
$submitDate = $newsData[1];
unset ($newsData['0']);
unset ($newsData['1']);
$newsContent = "";
$limitn=$itemperpage*$itemspage;
$itemindex=$limitn - 2;
foreach ($newsData as $value) {
$newsContent .= $value;
}
echo "<tr><th align='left'>$newsTitle</th>
<th class='right'>$submitDate</th></tr>";
echo "<tr><td colspan='2'>".$newsContent."<br/></td></tr>";
}
echo "</table>";
Notice the array_slice:
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.