0

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?

1
  • 1
    $pages isn't an associative array, why are you using array_keys($pages)? Commented Oct 28, 2021 at 0:30

1 Answer 1

3

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
}
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.