How to loop multidimensional array in php

I think a good way to approach this is "bottom up", ie. work out what to do with the inner-most values, then use those results to work out the next-level-up, and so on until we reach the top. It's also good practice to write our code in small, single-purpose, re-usable functions as much as possible, so that's what I'll be doing.

Note that I'll assume your data is safe [ie. it's not been provided by a potentially-malicious user]. I'll also assume that the keys "ime" and "opi" are meant to match the "name" and "description" of the other arrays ;]

We can ignore the innermost strings themselves, since we don't need to modify them. In that case the inner-most structure I can see are the individual links, which are arrays containing a 'URL' value. Here's some code to render a single link:

function render_link[$link] {
  return "{$link['URL']}";
}

This has reduced an array down to a string, so we can use it remove the inner-most layer. For example:

// Input
array['URL' => "//www.artist1.com"]

// Output
"//www.artist1.com"

Now we move out a layer to the 'links' arrays. There are two things to do here: apply "render_link" to each element, which we can do using "array_map", then reduce the resulting array of strings down to a single comma-separated string, which we can do using the "implode" function:

function render_links[$links_array] {
  $rendered_links = array_map['render_link', $links_array];
  return implode[', ', $rendered_links];
}

This has removed another layer, for example:

// Input
array[1 => array['URL' => "//www.artist1.com"],
      6 => array['URL' => "//www.artist1-2.com"]]

// Output
"//www.artist1.com, //www.artist1-2.com"

Now we can go out another level to an individual artist, which is an array containing 'name', 'description' and 'links'. We know how to render 'links', so we can reduce these down to a single string separated by linebreaks:

function render_artist[$artist] {
  // Replace the artist's links with a rendered version
  $artist['links'] = render_links[$artist['links']];

  // Render this artist's details on separate lines
  return implode["\n
\n", $artist]; }

This has removed another layer, for example:

// Input
array['name'        => 'ARTIST 1',
      'description' => 'artist 1 desc',
      'links'       => array[
         1          => array[
           'URL'    => '//www.artist1.com']
         6          => array[
           'URL'    => '//www.artist1-2.com']]]

// Output
"ARTIST 1
 
artist 1 desc
//www.artist1.com, //www.artist1-2.com"

Now we can move out a layer to the 'artists' arrays. Just like when we went from a single link to the 'links' arrays, we can use array_map to handle the contents and implode to join them together:

function render_artists[$artists] {
  $rendered = array_map['render_artist', $artists];
  return implode["\n

\n", $rendered]; }

This has removed another layer [no example, because it's getting too long ;] ]

Next we have an event, which we can tackle in the same way we did for the artist, although I'll also remove the ID number and format the title:

function render_event[$event] {
  unset[$event['eventID']];
  $event['eventTitle'] = "{$event['eventTitle']}";
  $event['artists']    = render_artists[$event['artists']];
  return implode["\n
\n", $event]; }

Now we've reached the outer array, which is an array of events. We can handle this just like we did for the arrays of artists:

function render_events[$events] {
  $rendered = array_map['render_event', $events];
  return implode["\n

--

", $rendered]; }

You might want to stop here, since passing your array to render_events will give you back the HTML you want:

echo render_events[$my_data];

However, if we want more of a challenge we can try to refactor the code we've just written to be less redundant and more re-usable. One simple step is to get rid of render_links, render_artists and render_events since they're all variations on a more-general pattern:

function reduce_with[$renderer, $separator, $array] {
  return implode[$separator, array_map[$renderer, $array]];
}

function render_artist[$artist] {
  $artist['links'] = reduce_with['render_link', ', ', $artist['links']];
  return implode["\n
\n", $artist]; } function render_event[$event] { unset[$event['eventID']]; $event['eventTitle'] = "{$event['eventTitle']}"; $event['artists'] = reduce_with['render_artist', "\n

\n", $event['artists']]; return implode["\n
\n", $event]; } echo reduce_with['render_event', "\n

--

", $my_data];

If this is part of a larger application, we may want to tease out some more general patterns. This makes the code slightly more complex, but much more re-usable. Here are a few patterns I've spotted:

// Re-usable library code

// Partial application: apply some arguments now, the rest later
function papply[] {
  $args1 = func_get_args[];
  return function[] use [$args1] {
    return call_user_func_array[
      'call_user_func',
      array_merge[$args1, func_get_args[]]];
  };
}

// Function composition: chain functions together like a[b[c[...]]]
function compose[] {
  $funcs = array_reverse[func_get_args[]];
  $first = array_shift[$funcs];
  return function[] use [$funcs, $first] {
    return array_reduce[$funcs,
                        function[$x, $f] { return $f[$x]; },
                        call_user_func_array[$first, func_get_args[]]];
  };
}

// Transform or remove a particular element in an array
function change_elem[$key, $func, $array] {
  if is_null[$func] unset[$array[$key]];
  else $array[$key] = $func[$array[$key]];
  return $array;
}

// Transform all elements then implode together
function reduce_with[$renderer, $separator] {
  return compose[papply['implode', $separator],
                 papply['array_map', $renderer]];
}

// Wrap in HTML
function tag[$tag, $text] {
  return "{$text}";
}

// Problem-specific code

function render_link[$link] {
  return "{$link['URL']}";
}

$render_artist = compose[
  papply['implode', "\n
\n"], papply['change_elem', 'links', papply['reduce_with', 'render_link', ', ']]; $render_event = compose[ papply['implode', "\n
\n"], papply['change_elem', null, 'eventID'], papply['change_elem', 'eventTitle', papply['tag', 'strong']], papply['change_elem', 'artists', papply['reduce_with', $render_artist, "\n

\n"]]]; echo reduce_with[$render_event, "\n

--

", $my_data];

How do you loop through a multidimensional array in PHP?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.

How do you use each loop in a multidimensional array?

For example, write the foreach loop where the $bikes variable is the array. Set the $number variable as key and the $bike variable as value. Next, write another foreach loop inside the just created loop. In the nested loop, write the $bike variable as an array and set the $num and $value as key and value.

What is multi dimensional array in PHP?

A multidimensional array is an array containing one or more arrays. 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.

How can we store multidimensional array in database using PHP?

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column. ... PHP Multidimensional Array Example..

Chủ Đề