phparraystreearray-walk

PHP Can't print all keys name in array with array_walk()


My gallery folder has this structure:

/YEAR/MONTH/DAY/FILE

Then, i am going to print them in my website. I have a function that gets all files in a big array, with this struct:

Array
(
    [2017] => Array
        (
            [01] => Array
                (
                    [01] => Array
                        (
                            [0] => yo.jpg
                        )

                )

        )

    [2016] => Array
        (
            [02] => Array
                (
                    [01] => Array
                        (
                            [0] => yo.jpg
                        )

                )

            [01] => Array
                (
                    [03] => Array
                        (
                            [0] => timed-photos10.jpg
                        )

                    [01] => Array
                        (
                            [0] => yo.jpg
                        )

                )

        )

)

Then, i have made a new function for printing this images, and i need to get their path reading all their array keys.

Here is my function:

// ...
array_walk($mediaList, array($this, 'generateMedia'));      

public function generateMedia(&$value, $key)
{
    if(is_array($value))
    {
        echo $key . "/";
        array_walk($value, array($this, 'generateMedia'));
    }
    else
    {
        echo $value . "<br>";
    }
}

The problem comes when an array has more than 1 array.

The result i have is the next:

2017/01/01/yo.jpg
2016/02/01/yo.jpg
01/03/timed-photos10.jpg
01/yo.jpg

As you can see, the first and second record are ok, but the third and fourth are incorrect, because those elements has more than 1 array.

I have been trying different things but i can't resolve it.

What can i do?

Thank you!


Solution

  • Haven't testet your code but this would work:

    foreach ($mediaList as $year => $months) {
      foreach ($months as $month => $days) {
        foreach ($days as $day => $files) {
          foreach ($files as $key => $file) {
            echo $year . '/' . $month . '/' . $day . '/' . $file;
          }
        }
      }
    }