Array Problem

Discussion in 'PHP' started by scottlpool2003, Jul 13, 2012.

  1. #1
    I need to split an array up evenly or as close as possible.

    E.g. I have 128 items in an array, I need to split it up to show on 3 pages, how do it while keeping the remainder 8 on page 3?
     
    scottlpool2003, Jul 13, 2012 IP
  2. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #2
    You'll have 42 items on pages 1 and 2 and 44 items on page 3.

    
    for($i = 0; $i < 3;  $i++)
      for($j = 0; $j < 42; $j++) {
        //do what you want on each page here
      }
      //do what you want to go to the next page here
    }
    
    PHP:
     
    Rukbat, Jul 13, 2012 IP
  3. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #3
    
    $arr = Array( /* YOUR ITEMS HERE */ ); //assumed
    $arr = array_chunk($arr, 110); //so the last chunk has 8 items
    
    $page = intval($_GET['page']); #assumed getting page id from GET
    
    if ($page <= 0 or $page > count($arr))
       $page = 1
    
    #now display the array chunk for this page
    print_r(
       $arr[--$page];
    );
    PHP:

    I did not test but I am certain it works.

    Stay well....
     
    Vooler, Jul 14, 2012 IP
  4. mastjaat

    mastjaat Member

    Messages:
    64
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #4
    you must have to use for each().
    function to solve this problum
     
    mastjaat, Jul 14, 2012 IP
  5. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #5
    Let me correct you Sir.
    There's absolutely no need to use "foreach" loop, as "array_chunk" splits the array among chunks of desired size.
     
    Vooler, Jul 14, 2012 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #6
    Can you define 'keeping'? Are you simply saying split them up to show on one HTML send using some form of page break (in which case yes, array_chunk) or are you referring to holding onto the results for a separate HTML call/send?

    If the latter, how are you building that array?
     
    deathshadow, Jul 14, 2012 IP