Reputation: 154
I have a multidimensional array that I am trying to work with, here is what it looks like.
$states = array(
"California" => array(
"state" => "California",
"abbr" => "CA",
"city" => "Sacramento",
"county" => "Sacramento",
"zip" => "95632"
),
"Washington" => array(
"state" => "Washington",
"abbr" => "WA",
"city" => "Seattle",
"county" => "King",
"zip" => "98101"
),
"Texas" => array(
"state" => "Texas",
"abbr" => "TX",
"city" => "San Antonio",
"county" => "Bexar",
"zip" => "78251"
),
"Florida" => array(
"state" => "Florida",
"abbr" => "FL",
"city" => "Orlando",
"county" => "Orange",
"zip" => "32801"
),
);
When I run a foreach loop to get the keys from the first level of the arrays I get the expected output of
California Washington Texas Florida
However I need to access the second level of the array. For example I need California['abbr'] so this is the code I run:
foreach (array_keys($states) as $state) {
echo $state['abbr'];
}
Instead of getting
CA WA TX FL
like I would expect I'm getting
C W T F
Any ideas on what I'm doing wrong?
Upvotes: 0
Views: 56
Reputation: 833
Only cut out array_keys
. You need whole element of that array, not only keys of array.
foreach ($states as $state)
{
echo $state['abbr'];
}
Upvotes: 0
Reputation: 40628
You can use two foreach in order to access the elements inside each cities (array). That's not the fastest way but it's good to know it.
// access the first layer
foreach($states as $state)
{
// access the second layer
foreach($state as $key => $element)
{
// if the key is equal to 'abbr', echo it's value
echo ($key == 'abbr') ? $state[$key] : '';
echo ' ';
}
}
This will output:
CA WA TX FL
Upvotes: 1
Reputation: 15364
array_keys($states)
is returning
array("California", "Washington", "Texas", "Florida")
So the foreach
loop is echoing just the first character of each state. Loop through the entire array instead of just the keys:
foreach ($states as $name => $details) {
echo $details['abbr'];
}
Upvotes: 1
Reputation: 5062
foreach(array_keys($states) as $state) {
echo $state;
}
Will echo the keys, because you're looping over the keys, not the array. To get the abbreviation, you should do
foreach($states as $state) {
echo $state['abbr'];
}
If you want to loop over both the key and the value at the same time, try this
foreach($states as $key=>$state) {
echo "$key: {$state['abbr']}";
}
Upvotes: 1
Reputation: 317
Just:
foreach($states as $state) {
foreach($state as $v) {
echo $v['abbr'];
}
}
Upvotes: 0