Skip to content
Advertisement

Generate markup based on multidimensional array

I have the following multidimensional array:

$pages = array(
  array(
    "icon" => "",
    "subheader" => "Insights",
    "url" => "/insights/",
  ),
  array(
    "icon" => "",
    "subheader" => "Statistics",
    "url" => "/statistics/",
  ),
);

I’m trying to loop through the array and create cards with the above. Here’s how I’m looping through the array:

<?php
  $keys = array_keys($pages);
  for($i = 0; $i < count($pages); $i++) {
    foreach($pages[$keys[$i]] as $key => $value) { ?>

      <div class="productCard">
        <div class="productCard__header">
          <!-- url here-->
        </div>
        <div class="productCard__body">
          <!--subheader here -->
          <?php echo $value; ?>
        </div>
      </div>

    <?php }
  }
?>

The above loop renders out (for one item in the array):

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    Insights
  </div>
</div>

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    /insights/
  </div>
</div>

As you can see, it’s generating a separate productCard for each key.

The output I’m looking to achieve is:

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
    /insights/
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    Insights
  </div>
</div>

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
    /statistics/
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    Statistics
  </div>
</div>

Where am I going wrong?

Advertisement

Answer

You’re looping through the inner data of each element of the array

for() is looping through the main array, then your foreach() is iterating through the individual components.

Since your inner array is an associative array (the keys are defined by you), it means you can access them directly using [”] notation.

There are many different ways to do this, but I would suggest a single loop and then pull out your individual values:

Try this:

<?php
foreach($pages as $key => $value) { ?>

  <div class="productCard">
    <div class="productCard__header">
      <!-- url here-->
<?php echo $value['url']; ?>
    </div>
    <div class="productCard__body">
      <!--subheader here -->
      <?php echo $value['subheader']; ?>
    </div>
  </div>

<?php
}
?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement