在php中一次取10个数组元素?
问题描述:
echo "<table title='mxit:table:full' style='width: 100%' width='100%'><colgroup span='2' width='50%'></colgroup>";
foreach($arr['chart_data'] as $key => $element){
echo "<tr>";
foreach($element as $subkey => $subelement){
// $subelement =chop($subelement,'DIRECTSegment');
if($subkey++ < 2) {
if($key == 0)
{
echo "<td align='center;' style='color:white;'>$subelement</td>";
}
else if($subkey == 1)
{
echo "<td align='center;' style='color:white;'>$subelement</td>";
}
else
{
echo "<td align='center;' style='color:white;'><a href='getdata.php?key=$key'>".$subelement."</a></td>";
}
}
}
}
echo "</tr>";
echo "</table>";
How do i take only 10 elements of my array $arr['chart_data'] at a time ?
答
Anyway for all those who gave me negative votes and for my own betterment i solved my issue:
Here is what i did:
$totalfiles = count($arr['chart_data']);
$limit = 10;
$pages = ceil($totalfiles / $limit);
if (!isset($_GET['startrow']) or!is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int) $_GET['startrow'];
}
echo "<table title='mxit:table:full' style='width: 100%' width='100%'><colgroup span='2' width='50%'></colgroup>";
$data = array_slice($arr['chart_data'], $startrow, 10); // same as offset 0 limit 50 in sql
foreach($data as $key => $element) {
echo "<tr>";
foreach($element as $subkey => $subelement) {
$subelement = chop($subelement, 'DIRECTSegment');
if ($subkey++ < 2) {
if ($key == 0 && $startrow == 0) {
echo "<td align='center;' style='color:white;'>$subelement</td>";
} else if ($subkey == 1) {
echo "<td align='center;' style='color:white;'>$subelement</td>";
} else {
echo "<td align='center;' style='color:white;'><a href='getdata.php?key=$key'>".$subelement.
"</a></td>";
}
}
}
echo "</tr>";
}
echo "</table>";
/* free result set */
$result - > close();
}
/* close connection */
$mysqli - > close();
//now this is the link..
echo '<a href="'.$_SERVER['PHP_SELF'].
'?startrow='.($startrow + 10).
'">Next</a>';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo ' <a href="'.$_SERVER['PHP_SELF'].
'?startrow='.$prev.
'">Previous</a>';
Implemented paging and using array slice to display 10 elements at a time.
Thanks for all the help
答
Set a counter, and then break
the loop when $count
hits 10.
$count = 0;
/* loop here */
if ($count == 10) break;