array_slice is a built-in function in PHP to extract a continuous piece of elements from an array. Its basic syntax is:
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
$array : The array to be intercepted
$offset : Start position, 0 means starting from the first element
$length : The length of the intercept. If not specified, the default is to the end of the array.
$preserve_keys : Whether to keep the key name of the original array, default to false
Suppose we have an array containing 100 pieces of data, and now we need to implement the paging function of displaying 10 pieces of data per page.
Current page number $page (starting from 1)
Number of displayed characters per page $pageSize
Calculate the starting point of array intercept $offset = ($page - 1) * $pageSize
Just use array_slice to intercept the data of the current page from the array.
<?php
// Simulate data array
$data = range(1, 100); // Generate Include 1 arrive 100 array of numbers
// Get the current page number,The default is the first 1 Page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max($page, 1); // 确保Page码不小于 1
// 每Page显示多少条
$pageSize = 10;
// Calculate offset
$offset = ($page - 1) * $pageSize;
// use array_slice 截取当前Page的数据
$pageData = array_slice($data, $offset, $pageSize);
// 输出当前Page的数据
foreach ($pageData as $item) {
echo "Data Items:$item<br>";
}
// 生成分Page链接
$totalPages = ceil(count($data) / $pageSize);
echo "<div>";
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $page) {
echo "<strong>$i</strong> ";
} else {
echo "<a href=\"https://gitbox.net/page.php?page=$i\">$i</a> ";
}
}
echo "</div>";
?>
Accessing page.php?page=1 will display 10 pieces of data on page 1, accessing page.php?page=2 will display the content of page 2, and so on.
Using PHP's array_slice function combined with simple paging calculations, it can easily implement the paging function of arrays. Although paging data usually comes from a database in actual development, array_slice is a very lightweight and efficient solution for small data sets or cached data.
Remember, the key point is to calculate the correct offset $offset and control the number of bars displayed per page, so that the paging effect can be easily achieved.