Hi :-D
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:
Now usually we can just echo it out using foreach like this
now for a multidimensional array it will be even easier.
Look at the example below
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:
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.
Little Joke on the Side ;-)
Anyways lets build a nested foreach.
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.
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:
PHP Code:
Array
(
Array (
[fruit] => apple
[plant] => tree
[healthy] => yes
)
Array (
[fruit] => orange
[plant] => tree
[healthy] => yes
)
)
PHP Code:
foreach($array as $key => $value)
{
echo "$key \n $value \n";
}
Look at the example below
PHP Code:
foreach($value as $fruit)
{
printf("Fruit: %s Plant: %s Healthy: %s,
$fruit['fruit'],$fruit['plant'],$fruit['healthy']);
}
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:
PHP Code:
Array
(
Array
(
Array (
[fruit] => apple
[plant] => tree
[healthy] => yes
)
Array (
[fruit] => orange
[plant] => tree
[healthy] => yes
)
)
)
What is a Nested Foreach?
To make it Simple:
A nested foreach is a foreach inside a foreach.
Little Joke on the Side ;-)
Anyways lets build a nested foreach.
PHP Code:
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
}
}
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.