1

I have a multidimensional array that looks like the one below:

Array
(

[results] => Array
    (
        [0] => Array
            (
                [hotel_code] => 15ad7a
                [checkout] => 2018-04-26
                [checkin] => 2018-04-24
                [destination_code] => 1c6e0
                [products] => Array

                .... etc ....

            )
         [1] => Array
            (
                [hotel_code] => 193c6c
                [checkout] => 2018-04-26
                [checkin] => 2018-04-24
                [destination_code] => 1c6e0
                [products] => Array

                .... etc ....
            )

Wanting to create a simple pagination of the results, taking from the array 15 records at a time, through the following code I can recover the first 15 records.

$i = 0;
foreach($data['results'] as $key=>$val){
$i++;
$selez_hotel_code = '' . $val['hotel_code'] . '';
if($i == 15) break;
}

Now, how can I get the next 15 values from the array? I tried to start the foreach directly from record 15, setting it as follows

$i = 0;
foreach($data['results'][14]['hotel_code'] as $val){
$i++;
$selez_hotel_code = '' . $val . '';
if($i == 15) break;
}

but it did not work.

3
  • 1
    Its better to use for loop for this type of situation Commented Apr 5, 2018 at 9:30
  • Ok. But I do not know how to determine that the loop must start from level 14 of the array. Commented Apr 5, 2018 at 9:34
  • You have to send the start count number from the UI by which you will determine from where to start the loop Commented Apr 5, 2018 at 9:36

2 Answers 2

3

You could use for loop, to specify the start and the end:

$start = 15 ;
$length = 15 ;
$max = count($data['results']);
for ($idx = $start; $idx < $start + $length && $idx < $max; $idx++) {
    $val = $data['results'][$idx]['hotel_code'] ;
    $selez_hotel_code = $val ;
}

Note that I've added a verification to avoid to loop over the maximum of results ($idx < $max).

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! By changing the code according to my needs, it works perfectly. Thanks so much.
0

You can use $_GET to paginate. Just have a for loop that uses this param if set, 0 if not. Something like this:

$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
for ($i = $page; $i < ($page + 15); $i++) {
    // $data['results'][$i] . . .
}

And when clicking on "next page" or whatever you're using, set the page param

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.