Jump to content

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?

Edited by -Karl-

You could run through the array once:

$left = array();
$right = array();
$l = true;
foreach ( $arr as $val ) {
if ( $l ) {
$left[] = $val;
} else {
$right[] = $val;
}
$l = !$l;
}

Hmm, but how would I return it from the function?

Edited by -Karl-

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!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.