-1

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

到目前为止的脚本。

$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>";
?>
4

1 回答 1

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 />';
}
于 2013-01-14T11:14:04.567 回答