Warning: include(.../cache/template/template63867.php): failed to open stream: No such file or directory in /home/codingta/public_html/includes/vb5/template.php on line 328 Warning: include(): Failed opening '.../cache/template/template63867.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/codingta/public_html/includes/vb5/template.php on line 328 Handling Multidimensional Arrays - Coding-Talk

Handling Multidimensional Arrays

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Handling Multidimensional Arrays

    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:
    PHP Code:
    Array
    (
    Array (
     [
    fruit] =&gtapple
    [plant] =&gttree
    [healthy] =&gtyes
    )
    Array (
    [
    fruit] =&gtorange
    [plant] =&gttree
    [healthy] =&gtyes
    )

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

    PHP Code:
    foreach($array as $key =&gt$value)
    {
    echo 
    "$key \n $value \n";

    now for a multidimensional array it will be even easier.

    Look at the example below

    PHP Code:
    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:

    PHP Code:
    Array
    (
      Array
    (
    Array (
    [
    fruit] =&gtapple
    [plant] =&gttree
    [healthy] =&gtyes
    )
    Array (
    [
    fruit] =&gtorange
    [plant] =&gttree
    [healthy] =&gtyes
    )
    )

    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.

    Click image for larger version

Name:	WPNGO8N.jpg
Views:	1
Size:	95.6 KB
ID:	148645

    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
    }

    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.
Working...
X