Jump to content

Recommended Posts

Posted

I'm trying to add a class and <div> tags to part of an array. It's an array of different fields (images and text) from a number of child pages. I want the result of each child to be styled individually, but so far, I've only been able to style the whole array or each individual item.

I tried:

<div class="my-class">
<?php
foreach($page->children as $child):
	foreach($child->images as $image):
		echo "<img src='$image->url'/>";
	endforeach; 
endforeach;
?>
</div>

which adds a class to the whole array.

Or: 

<?php
foreach($page->children as $child):
	foreach($child->images as $image): 
		echo "<div class='my-class'> <img src='$image->url'/></div>";
	endforeach; 
endforeach;
?>

which adds a class to each individual field. I understand that I have to add something to the code that divides the array for each child page, but how?

Posted

Hello Roderick,

are you searching for this solution?

<?php
foreach($page->children as $child):
?>
	<div class="my-class">
<?php
	foreach($child->images as $image):
		echo "<img src='$image->url'/>";
	endforeach;
?>
	</div>
<?php
endforeach;
?>

Regards, Andreas

Posted

wouldn't this code do the same ?

<?php
foreach($page->children as $child):

	<div class="my-class">

	foreach($child->images as $image):
		echo "<img src='$image->url'/>";
	endforeach;

	</div>

endforeach;
?>
Posted

wouldn't this code do the same ?

<?php
foreach($page->children as $child):

	<div class="my-class">

	foreach($child->images as $image):
		echo "<img src='$image->url'/>";
	endforeach;

	</div>

endforeach;
?>
<?php
foreach($page->children as $child) {
    echo "<div class='my-class'>";
    foreach($child->images as $image) { echo "<img src='$image->url'/>"; }
    echo "</div>";
}
?>

???

Posted

Tom's suggestion works, thanks.

It's a bit confusing to me to see people using either curly brackets or a colon when calling foreach, but I guess it's up to the user to choose their preferred method. 

Posted

My suggestion does the same as Tom's, but I forgot, that you would like to echo the HTML code.

Personally, I don't like to echo every bit of HTML, but as you said, it is a matter of preference.  ;)

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
  • Recently Browsing   0 members

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