Jump to content

Nesting foreach with multimensional arrays


Nitz

Recommended Posts

Hey guys,

 

I'm brand new to PHP and I'm running through PHP 6 and MySQL 5 from Peachpit press and I'm having troubles with one of their example scripts. Firefox says the problem is with line 40 but I can't see anything wrong:

 

http://pastebin.com/7dpNfyS1

 

Thanks for your time

Sorry I'm not sure what you mean. I used the first foreach to put the keys of $n_america in $country and the values in $list (which are actually arrays.) That part is working fine.

 

I want the second foreach to pull the key from each array in $list and put them in $k and put the value in $v. This part doesn't seem to work

 

$n_america = array(
'Mexico' => '$mexico',
'United States' => '$us',
'Canada' => '$canada'
);

foreach ($n_america as $country => $list) {
echo "<h2>$country</h2><ul>";

foreach ($list as $k => $v) {
	echo "<li>$k - $v</li>";
}
echo '</ul>';
}

The problem is with the $n_american array. You are apparently wanting each "country" index to have a value of the country arrays created above. But, you are encasing the country array variables withing single quotes. variables are not interpreted when enclosed within single quotes. So, the value of the 'Mexico' index is the literal string of "$mexico" not the array of Mexican territories. But, I'm not sure it would work the way you want using doub;e quotes either. Just use this:

 

                        $n_america = array(
                                'Mexico' => $mexico
                                'United States' => $us,
                                'Canada' => $canada
                        );

The problem is with the $n_american array. You are apparently wanting each "country" index to have a value of the country arrays created above. But, you are encasing the country array variables withing single quotes. variables are not interpreted when enclosed within single quotes. So, the value of the 'Mexico' index is the literal string of "$mexico" not the array of Mexican territories. But, I'm not sure it would work the way you want using doub;e quotes either. Just use this:

 

                        $n_america = array(
                                'Mexico' => $mexico
                                'United States' => $us,
                                'Canada' => $canada
                        );

 

You're right! I can't believe I missed that haha I've been going over this for hours. Thanks so much!

Archived

This topic is now archived and is closed to further replies.

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