Jump to content

Alternating Array Between Left And Right


-Karl-

Recommended Posts

Hello,

 

I need a more efficient way of alternating an array in order to display them left and right.

 

At the moment I have my HTML:

<div class="left">
 //This floats everything within the div to the left
 //Echo buildLeft
</div>
<div class="right">
 //This floats everything within the div to the right
 //Echo buildRight
</div>

 

Then I have the following PHP code in order to take the current array, which is all the results and manipulate it:

 function buildLeft($array) {
	 $new_array = array();
	 $i = 0;
	 $count = count($array);
	 while($i < $count) {
		 $new_array[] = $array[$i];
		 $i = $i+2;
	 }
	 return $new_array;
 }

 function buildRight($array) {
	 $new_array = array();
	 $i = 1;
	 $count = count($array);
	 while($i < $count) {
		 $new_array[] = $array[$i];
		 $i = $i+2;
	 }
	 return $new_array;
 }

 

The code works fine and does what I need it to do, but I just don't think it's very efficient, especially when the beginning array could be quite large, then I'm running it through both of these functions.

 

Any ideas?

Nevermind, fixed it myself:

 

    function buildPosts($array) {
	    $new_array = array('left' => array(), 'right' => array());
	    $i = 0;
	    foreach($array as $val) {
		    if($i == 0) {
			    $new_array['left'][] = $val;
			    $i = 1;
		    } else {
			    $new_array['right'][] = $val;
			    $i = 0;
		    }
	    }
	    return $new_array;
    }

 

Thanks for the advice though guys!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.