简体   繁体   中英

Multidimensional Array Prev Next with PHP

I'm new to PHP and have been at this for days with no luck. I want to identify the current page, and then have a link for plus one and minus one to do Prev-Next links.

The array is based on .md files in a folder. It can grow or shrink as I add blog posts. This is the current test array (minus other key-value pairs):

 $totalPages =  Array
(
    [0] => TD_Page Object
        (
            [keyword] => art
        )

    [1] => TD_Page Object
        (
            [keyword] => but
        )

    [2] => TD_Page Object
        (
            [keyword] => car
        )

    [3] => TD_Page Object
        (
            [keyword] => dat
        )

    [4] => TD_Page Object
        (
            [keyword] => eek
        )

    [5] => TD_Page Object
        (
            [keyword] => fit
        )

Since keywords act as the page URI via PHP routing, I want the end result to look conceptually something like this:

<a href="/blog/<?= echo next($keyword) ?>">Prev</a> 
<a href="/blog/<?= echo prev($keyword) ?>">Prev</a> 

I want to check for the current page, then add a pointer to up or down one in the array. If it's the first or last post, then no link will appear for the corresponding prev or next link.

Use array_column then array_search to find the index. then -/+ on that.

Example:

<?php
$data = [
    (object)['keyword' => 'art'],
    (object)['keyword' => 'but'],
    (object)['keyword' => 'car'],
    (object)['keyword' => 'dat'],
    (object)['keyword' => 'eek'],
    (object)['keyword' => 'fit']
];

$current = array_search('car', array_column($data, 'keyword'));

echo 'Current:'.$data[$current]->keyword.PHP_EOL;
echo 'Next:'.$data[$current+1]->keyword.PHP_EOL;
echo 'Prev:'.$data[$current-1]->keyword.PHP_EOL;

Result:

Current:car
Next:dat
Prev:but

https://3v4l.org/lOZ8e

Don't forget to check that it has a next or previous link, with isset() etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM