使用关联数组的分页

时间:2013-01-14 11:07:26

标签: php pagination

我有以下脚本,它将从数组中分页结果...但仅在使用数字键值时。是否可以使用键的字符串值修改此脚本以使用关联数组?我需要按照字母顺序对数组进行排序,最终的目的是以字母顺序分页。

到目前为止的脚本。

$my_array = array(0 => 'a', 1 => 'b', 2 => 'c'); // THIS WORKS FINE

//$my_array = array('a' => 'a', 'b' =>'b', 'c'=>'c'); // THIS DOESN'T WORK

$arr = $my_array; 

$rows_per_page = 1;

$numrows = count($arr);

// Calculate number of $lastpage
$lastpage = ceil($numrows/$rows_per_page);

// condition inputs/set default
if (isset($_GET['pageno'])) {
   $pageno = $_GET['pageno'];
} else {
   $pageno = 1;
}

// validate/limit requested $pageno
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
   $pageno = $lastpage;
}
if ($pageno < 1) {
   $pageno = 1;
}

// Find start and end array index that corresponds to the requested pageno
$start = ($pageno - 1) * $rows_per_page;
$end = $start + $rows_per_page -1;

// limit $end to highest array index
if($end > $numrows - 1){
    $end = $numrows - 1;
}

// display array from $start to $end
for($i = $start;$i <= $end;$i++){
    echo $arr[$i] . '<br />';
}
echo "<p style='text-align:center;'>";

// first/prev pagination hyperlinks
if ($pageno == 1) {
   echo " FIRST PREV ";
} else {
   echo " <a href='?pageno=1'>FIRST</a> ";
   $prevpage = $pageno-1;
   echo " <a href='?pageno=$prevpage'>PREV</a> ";
}

// Display current page or pages
echo " ( Page $pageno of $lastpage ) ";

// next/last pagination hyperlinks
if ($pageno == $lastpage) {
   echo " NEXT LAST ";
} else {
   $nextpage = $pageno+1;
   echo " <a href='?pageno=$nextpage'>NEXT</a> ";
   echo " <a href='?pageno=$lastpage'>LAST</a> ";
}

echo "</p>";
?>

1 个答案:

答案 0 :(得分:0)

您指的是数字索引的关联数组,替换

for($i = $start;$i <= $end;$i++){
    echo $arr[$i] . '<br />';
}

使用:

$arr_keys = array_keys($arr);
for($i = $start;$i <= $end;$i++){
    echo '-'.$arr[$arr_keys[$i]] . '<br />';
}