2011-01-25 46 views
0

我有一个数组,将呈现数据将用于显示为异教徒。如何从多个数组中分页并计算总数?

$display_array = Array (
       [0] => Array 
        (
        [0] => 1 
        [1] => 2 
        [2] => 5 
        [3] => 5 
       ) 

       [1] => Array 
        (
        [0] => 1 
        [1] => 2 
        [2] => 5 
        [3] => 5 
       ) 

       [2] => Array 
        (
        [0] => 1 
        [1] => 2 
       ) 

       [3] => Array 
        (
        [0] => 1 
        [1] => 2 
       ) 

      ) 

I WANT做PAGANATION得到预期的结果是这样的:

IF我定义$ show_per_page = 2;

呼叫paganation($ display_array,1); //第1个第一页输出:

1 
2 

呼叫paganation($ display_array,2); //翻页2 OUTPUT:

5 
    5 
    Total:13 // total appear here 


....//next page n 

如果我定义了$ show_per_page = 3;

paganation($ display_array,1); //页面1第一页输出:

1 
    2 
    5 

paganation($ display_array,2); //翻页2 OUTPUT:

5 
    Total:13//Now total appear here 
    1 
    2 

paganation( $ display_array,3); //下3页OUTPUT:

5 
5 
Total:10 // total appear here 
1 

IF我定义$ show_per_page = 12; 呼叫paganation($ display_array,1); //第1个第一页输出:这里

1 
2 
5 
5 
total:13 // total here 
1 
2 
5 
5 
total:13 // total here 
1 
2 
total:3 //total 
1 
2 
total:3 //total 

人有什么想法?

+0

而且正是你想通过发布2个类似的问题来实现呢?只要坚持你的原始问题,并修改那一个:http://stackoverflow.com/questions/4793997/how-to-do-a-pagination-from-array – wimvds 2011-01-25 16:55:10

+0

是的,但我发现我必须改变我的数据结构。所以当我的例子$ show_per_page = 12.one的情况下我没有任何问题,我得到了改变输入数组的建议,此时人们会明白我想要什么,我有一个很好的答案:)而且你现在明白我的问题了吗? – kn3l 2011-01-25 16:59:24

回答

2

幼稚的东西(因为它没有跳过有效的前几页):

// array to display 
// page to show (1-indexed) 
// number of items to show per page 
function pagination($display_array, $page, $show_per_page){ 
    $start = $show_per_page * ($page-1); 
    $end = $show_per_page * $page; 
    $i = 0; 
    foreach($display_array as $section){ 
     $total = 0; 
     foreach($section as $value){ 
      if($i >= $end){ 
       break 2; // break out of both loops 
      } 

      $total += $value; 
      if($i >= $start){ 
       echo $value.'<br>'; 
      } 
      $i++; 
     } 
     if($i >= $start){ 
      echo 'total:'.$total.'<br>'; 
     } 
     if($i >= $end){ 
      break; 
     } 
    } 
}