I thought that I understood php arrays, but it seems I don't :( This is my code:
<?php
// Create a magazines array
$magazines = array();
// Put 5 magazines on it
for($x=0;$x<5;$x++)
$magazines[] = "Magazine " . $x ;
// Associate articles array to each magazine
foreach($magazines as $magazine){
$articles[$magazine] = array();
for($x=0;$x<3;$x++)
$articles[$magazine] = $magazine . " - Article " . $x ;
}
// List them all
foreach($magazines as $magazine){
echo $magazine . " has these articles: <br>";
foreach($articles[$magazine] as $article)
echo $article . "</br>";
}
?>
It only prints the magazines, not the articles inside each magazine. It's clear there is something I don't get about nested foreach loops. Could you please help me? What am I doing wrong? Thanks in advance! :)
You missed the [] in the nested loop:
<?php
// Create a magazines array
$magazines = array();
// Put 5 magazines on it
for($x=0;$x<5;$x++)
$magazines[] = "Magazine " . $x ;
// Associate articles array to each magazine
foreach($magazines as $magazine){
$articles[$magazine] = array();
for($x=0;$x<3;$x++)
$articles[$magazine][] = $magazine . " - Article " . $x ;
}
// List them all
foreach($magazines as $magazine){
echo $magazine . " has these articles: <br>";
foreach($articles[$magazine] as $article)
echo $article . "</br>";
}
?>
This snippet should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With