Manage a 4 dimensional array or a 5 dimensional with foreach statement in php

ThunderBoy

I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.

A very simple example below

  $documents = array(
    array(
         "name"=>"Markos",
        "lastname"=>"papadopoulos",
        "country"=>"Greece",
        "nationality"=>"greek",
        "job"=>"web developer",
        "hobbies"=>array(
                "sports"=>"boxing",
                "others"=>array(
                        "freetime"=>"watching Tv"
                )
        )

    )
);

foreach($documents as $document){
    echo $document['name']."<br>"
        .$document['lastname']."<br>"
        .$document['country']."<br>"
        .$document['nationality']."<br>"
        .$document['job']."<br>";

            foreach ($document['hobbies'] as $key=>$value){
                echo $key." ".$value."<br>";

                    foreach ($value['others'] as $subkey=>$subvalue){
                        echo $subkey['freetime'];
                    }

                }
}

I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.

β.εηοιτ.βε

In PHP, foreach actually have two syntaxes:

  1. foreach($array as $element) this might means $element ends up being an array
  2. foreach($array as $key => $value) this means that key will never be an array, it is what the key, so what you have before the => in your array, while $value can be an array.

Here is the way to follow the first syntax, mind that you don't even have to nest foreach here, as pointed out by @Nathanael's comment what you have in your array is mostly scalar, not really nested arrays.

foreach($documents as $document){
  echo $document['name']."<br>".
    $document['lastname']."<br>".
    $document['country']."<br>".
    $document['nationality']."<br>".
    $document['job']."<br>".
    $document['job']."<br>".
    $document['hobbies']['sports']."<br>".
    $document['hobbies']['others']['freetime'];
}

If you want to go in the second syntax, then it would be even better to make a recursion:

function display_multi_level_array($array) {
  foreach($array as $key => $value){
    if(is_array($value)) {
       display_multi_level_array($value);
       continue;
    }

    echo $key." ".$value."<br>";
  } 
}

display_multi_level_array($documents);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related