Jump to content

iteration array


ngrmm
 Share

Recommended Posts

i have an array of pages $allPages

how can i divide them in two groups of odd and even?
right now i have them in one line. but i want to have them in two groups.

			$allPages = $xPage->children;

			$counter = ""; 
			foreach ( $allPages as $item ) {
				$counter +=1; 
				if($counter == 1) { 
					echo "<div class='columns-wrapper odd'>$item</div>";
				}
				elseif($counter == 2) { 
				$counter = 0; 
			    	echo "<div class='columns-wrapper even'>$item</div>";
			   	} 
			} 

is there a easy way in processwire to get these two arrays?

$allPages_odd
$allPages_even

 

Link to comment
Share on other sites

i manage to get it this way. but i think there should be a better way

 

			echo "<div class='items'>";
				$odd = array();
				$even = array();
				echo "<div class='odd'>";
				foreach ($allPages as $k => $v) {
			   		if ($k % 2 == 0) {
			        	$even[] = $v;
						echo "<div>$v</div>";
			    	}
				}
				echo "</div>";
				echo "<div class='even'>";
				foreach ($allPages as $k => $v) {		   
				   	if ($k % 2 !== 0) {
				        $even[] = $v;
				        echo "<div>$v</div>";
				    }
				}
			echo "</div>";	

 

Link to comment
Share on other sites

@ngrmm

Your solution looks good, since the mod operator is the fastest way to determine even/ odd in PHP, but I would loop only once.

$even = '';
$odd = '';
foreach ($allPages as $k => $v) {
    if ($k % 2) {
        $even .= "<div>$v->title</div>";
    } else {
        $odd .= "<div>$v->title</div>";
    }
}
echo "<div class='items'>";
echo "<div class='odd'>";
echo $odd;
echo "</div>";
echo "<div class='even'>";
echo $even;
echo "</div>";
echo "</div>";    

 

  • Like 4
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...