Idea Project
Idea Project

Reputation: 49

PHP array multidimensional: foreach starting from determinate level

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.

Upvotes: 1

Views: 46

Answers (2)

Bojan Radaković
Bojan Radaković

Reputation: 440

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

Upvotes: 0

Syscall
Syscall

Reputation: 19780

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).

Upvotes: 3

Related Questions