0

I was wondering if anyone could help me generate previous/next buttons based on an array of all items.

This is my basic array:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => ITEM 1
        )

    [1] => stdClass Object
        (
            [id] => 5
            [name] => ITEM 2
        )

    [2] => stdClass Object
        (
            [id] => 6
            [name] => ITEM 3
        )

    [3] => stdClass Object
        (
            [id] => 7
            [name] => ITEM 4
        )   
)

What I'm trying to do is:

Viewing: ITEM 1 Previous Button: ITEM 4 Next Button: ITEM 2

Viewing: ITEM 2 Previous Button: ITEM 1 Next Button: ITEM 3

Viewing: ITEM 3 Previous Button: ITEM 2 Next Button: ITEM 4

etc

I guess I'm really trying to turn my original array into another array of prev/next based on which item I am viewing.. if that makes sense..? Any help would be greatly appreciated!

1
  • I don't really need the buttons created btw, I just need the previous / next IDs (and names) from the array so I can create the buttons.. Commented Nov 10, 2011 at 5:25

1 Answer 1

1

There are many ways to do this, but you could use array_shift / array_push to cycle through the array of things. This doesn't use the exact array you mentioned, but it should get you close to your solution.

<?php

function next_and_prev($current, $a) {
    while (true) {
        /* Test for item at 2nd position in the array, so if we hit a match,
           we can just grab the first and third items as our prev/next results.

           Since we are mutating the array on each iteration of the loop, the
           value of $a[1] will change each time */
        if ($current == $a[1]) {
            print "Prev: " . $a[0] . "\n";
            print "Next: " . $a[2] . "\n";
            return;
        }
        array_push($a, array_shift($a));
    }
}

print "with current of 1\n";
next_and_prev(1, array(1, 2, 3));

print "with current of 2\n";
next_and_prev(2, array(1, 2, 3));

This prints:

with current of 1
Prev: 3
Next: 2
with current of 2
Prev: 1
Next: 3

Keep in mind that this does no membership test, so if $current isn't in the array, you'll end up in an infinite loop. Also, I'll add the disclaimer that I'm sure there are probably better ways to do this, this is just one approach.

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.