Roderick Posted December 14, 2015 Posted December 14, 2015 I'm unable to get an array of all image url's when calling the underneath, even though several children contain multiple images. I only get the first image url of each child. Am I writing something wrong here? <?php foreach($page->children as $child): foreach($child->images as $image); echo $image->url; endforeach; ?> All image url's display fine on the child page itself when calling: <?php foreach($page->images as $image): echo $image->url; endforeach; ?>
diogo Posted December 14, 2015 Posted December 14, 2015 Try: <?php foreach($page->children as $child): foreach($child->images as $image): echo $image->url; endforeach; endforeach; ?> I kept the code similar to what you had so you understand the differences, but way of writing PHP is more suitable if you want to alternate PHP and direct HTML. For a simple echo it's better to just use brackets. I'm actually surprised that you don't get a PHP error with that code 2
Roderick Posted December 14, 2015 Author Posted December 14, 2015 Thanks @diogo. I see my mistakes now. Can you explain what you mean when you say 'just use brackets'? I'm new to all this.
diogo Posted December 14, 2015 Posted December 14, 2015 Glad I helped. I meant the most common way of writing loops in PHP. Using this same example: <?php foreach($page->children as $child) { foreach($child->images as $image) { echo $image->url; } } The for you used is common for when you are mixing PHP and HTML. Like this: <?php foreach($page->children as $child): ?> <article> <h2>Images from page: <?=$child->title?></h2> <div class="images"> <?php foreach($child->images as $image): ?> <img src="<?=$image->url?>" /> <?php endforeach ?> </div> </article> <?php endforeach ?> 1
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now