1

I'm doing a course content navigation (similar to udemy navigation). In my case in a simplified way through two buttons: prev and next. all this is in PHP

I'm getting the course content from the database into an array $contentNodes

these $contentNodes have the following data:

array (size=23)
  'id' => string '71822' (length=5)
  'content_type' => string '5' (length=1)
  'title' => string 'Glosario de términos 4' (length=23)
  'order_id' => string '37.00000' (length=8)
  'class_id' => null
  'course_id' => string '4765' (length=4)
  'status' => string '0' (length=1)
  'image_thumbnail' => null
  'items_count' => string '0' (length=1)
  'formatedTitle' => string 'glosario-de-terminos-4' (length=22)
  'checked' => boolean false
  'current' => int 0
  'tipo' => string 'pdf' (length=3)
  'link' => string '<a href="/student/course/text/12944?title=glosario-de-terminos-4">Glosario de términos 4</a>' (length=93)

I'm stuck in the logic to go through the array, going to next or previous, each time the buttons are clicked.

with a count($contentNodes) I know how many items are. I know what the first element is (thinking in the first element I don't need to show or enable the previous button—the same case for the next and last item.

I hope you can give me some advice or the best way to do this.

I really appreciate any help you can provide.

My current code:

<div class="col-12">
    <?php
    /*echo '<pre>';
    var_dump(count($contentNodes));
    echo '</pre>';*/
    foreach ($contentNodes as $key => $content) {
        echo '<pre>';
        var_dump($content, "FILA");
        echo '</pre>';
    }
    ?>
    <div class="row">
        <div class="col-6">
            <a href="#" class="btn btn-secondary btn-block" id="prev-page" data-page="">PREV</a>
        </div>
        <div class="col-6">
            <a href="#" class="btn btn-primary btn-block" id="next-page" data-page="">NEXT</a>
        </div>
    </div>
   
</div>

Here there is the view

enter image description here

1 Answers1

0

When clicking on any page, you get that page like courses/?page=2 or if none is set, you assume the first page.

$pageNumber = isset($_GET['page']) ? (int)$_GET['page'] : 1;

Pages:

$currentNode = $contentNodes[$pageNumber - 1]; // Array starts with zero, page number starts with 1

$previousNode = $pageNumber > 1 && isset($contentNodes[$pageNumber - 2]) // Make sure previous page exists
    ? $contentNodes[$pageNumber - 2] : null; // Otherwise set null

$nextNode = isset($contentNodes[$pageNumber]) ? // Make sure there is a another page
    $contentNodes[$pageNumber] : null; // If not, set to null
Daniel W.
  • 31,164
  • 13
  • 93
  • 151