728883902
728883902

Reputation: 507

Transplanting part of a multidimensional array to a new array using array_push() in PHP

I have an array called $results which looks something like this:

[41] => Array
    (
        [id] => 200
        [0] => 200
        [description] => Exercitationem quidem in soluta repellendus. Nihil rem eius doloribus error qui consequatur rerum. Ut ea et reprehenderit ea.
        [1] => Exercitationem quidem in soluta repellendus. Nihil rem eius doloribus error qui consequatur rerum. Ut ea et reprehenderit ea.
        [amount] => 2696.00
        [2] => 2696.00
        [event_class] => 6
        [3] => 6
        [datetime] => 1978-11-19 14:13:20
        [4] => 1978-11-19 14:13:20
    )

[42] => Array
    (
        [id] => 201
        [0] => 201
        [description] => Cupiditate repudiandae aliquid et aut vitae ipsum esse. Odit id debitis atque. Fugiat et dolores tempore officiis.
        [1] => Cupiditate repudiandae aliquid et aut vitae ipsum esse. Odit id debitis atque. Fugiat et dolores tempore officiis.
        [amount] => 23.00
        [2] => 23.00
        [event_class] => 3
        [3] => 3
        [datetime] => 2004-02-23 00:30:56
        [4] => 2004-02-23 00:30:56
    )

With the following code, I am trying to extract several consecutive records from a particular part of this array, and move them to a new array called $fields. This is for pagination.

// based off the desired page, calculate the lowest ID for the record that should be shown
$lower_bound = (int)($_GET['page'] * 10) - 10;

// calculate the highest ID to be shown
$upper_bound = (int)$lower_bound + 10;

$fields = array();
for($i=$lower_bound; $i<=$upper_bound; $i++) {
    $fields = array_push($results[$i]);
}

echo '<pre>';
print_r($fields);
echo '</pre>';

However, print_r($fields); returns nothing. Could anyone kindly suggest why this may be?

I am aware that the array_slice() function exists, however I need to approach the problem by means of the above.

Upvotes: 0

Views: 35

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

I haven't used array_push() in forever, and you're not using it properly. It takes two arguments, an array and the value to push onto the array. However, just use:

for($i=$lower_bound; $i<=$upper_bound; $i++) {
    $fields[] = $results[$i];
}

That being said, this is much simpler:

$fields = array_slice($results, $lower_bound, 10);

Upvotes: 2

Related Questions