SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    331
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help needed with array chunk

    Hi everyone,

    I'm hoping someone could please assist me with the following. I'd like to split the contents of an array into 2 equal columns. Each column should have a <div class="stylecol">'; followed by half of the array's contents.


    PHP Code:
    $explode explode("-"$row['names']);
    $chunk array_chunk($explode2);
    foreach (
    $chunk as $con ) {
    echo 
    '<div class="stylecol">
    <p>'
    .$con.'</p>
    </div>'
    ;


    Something isn't working...

    Thank you in advance!

  2. #2
    SitePoint Evangelist
    Join Date
    Oct 2005
    Location
    Michigan, USA
    Posts
    434
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You've told it you want the array split into groups of two like
    a,b
    c,d
    e,f
    g,h
    i,j

    but you're looking for two groups, right?
    a,b,c,d,e
    f,g,h,i,j

    I think maybe array_chunk() is not what you want. You didn't say what you're expecting so my assumptions might be off but maybe this can get you started if so.

    PHP Code:
    $explode explode("-"$row['names']);
    $final = array();
    $n floorcount$explode ) / );

    $final[] = array_slice$explode0$n );
    $final[] = array_slice$explode$n );

    foreach( 
    $final as $col ) {
      echo 
    '<div class="stylecol">';
      foreach( 
    $col as $name ) {
        echo 
    "<p>{$name}</p>";
      }
      echo 
    '</div>';

    I used array_slice() to cut the array into two pieces. I put those two arrays into a containing array so that we can loop through it and create a div for each piece.
    - Robert

  3. #3
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    331
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi QMonkey,

    thanks a lot! I'll try out the code a bit later.

  4. #4
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    331
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello QMonkey,

    your code is working perfectly. Thank you for taking the time to help me out!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •