Handling Multidimensional Arrays

Started on the old forum in August 2014 · view the original in the archive · old links redirect here

1 reply · 81 views · started 12 years ago · 2 min read

2 participants
djdevil89 Senior · 287 posts #1

Hi 😀

After my daughter was born last year i didnt Really have time for coding anymore.

Lately i started again and now i want to show you how to handle Multidimensional Arrays , the approach i am using here is called Nested Foreach .

It is not always required to use a Nested foreach as you will see later on.

Ok lets assume we have this Array:

Array
(
Array (
 [fruit] => apple
[plant] => tree
[healthy] => yes
)
Array (
[fruit] => orange
[plant] => tree
[healthy] => yes
)
)

Now usually we can just echo it out using foreach like this

foreach($array as $key => $value)
{
echo "$key \n $value \n";
}

now for a multidimensional array it will be even easier.

Look at the example below

foreach($value as $fruit)
{
printf("Fruit: %s Plant: %s Healthy: %s,
$fruit['fruit'],$fruit['plant'],$fruit['healthy']);
}

As you can see we only used the "as" we got rid of the "=>" . Why? Well i cant really tell you, as in my expierience it returns a empty string. Anyways, back on Topic.

Now Sometimes it might become even more confusing when we have a array like this:

Array
(
  Array
(
Array (
[fruit] => apple
[plant] => tree
[healthy] => yes
)
Array (
[fruit] => orange
[plant] => tree
[healthy] => yes
)
)
)

Here we will use what is called Nested Foreach .

What is a Nested Foreach?

To make it Simple: A nested foreach is a foreach inside a foreach.

WPNGO8N.jpg

Little Joke on the Side 😉

Anyways lets build a nested foreach.

foreach($value as $fruit)
{
foreach($fruit as $fruits)
{
///now i use printf you can also use echo to echo it out as mentioned upstairs
echo "$fruits[plant]"; //Example
}
}

Now this we can repeat as many times as needed depending on how nested the Array is.

Thats all i wanted to show for the moment.

I am sure there are better ways on to do this. But this is my personal Experience 🙂 hope it helped someone.

foreach ($_SERVER as $server => $value)
{
echo "$server is $value<br />";
}
CliftonSox Junior · 10 posts #2

I looked hi and lo for stuff on writing arrays to tables but nothin There must be a dead simple way to write a single or 2 dimensional array to a table? Peter

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close