PHP知识点练习之数组分页
这篇文章介绍了如何在PHP中实现数组分页查询。文章首先展示了一个示例,其中包含一些数字,并使用`array_slice`函数来获取这些数字的分页结果。接着,文章详细解释了`array_slice`函数的使用方式,包括如何指定起始位置、结束位置以及长度等参数。最后,文章强调了在使用`array_slice`函数时需要注意的一些细节,如是否保留键值对等。总结来说,这篇文章主要介绍了如何在PHP中通过`array_slice`函数实现数组的分页功能,同时提供了具体的示例代码和详细的解释,以便读者更好地理解和应用这一技术。

复习下知识点,PHP数组分页同样适用于任何语言,以及数据库分页查询

<?php

$arr = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
];
// 分页大小
$page_size = 3;
// 页码
$page = isset($_GET['p']) ? $_GET['p'] : 1 ;
// 偏移量
$start = ($page - 1) * $page_size;

$data = array_slice($arr, $start,$page_size);

echo "<pre>";
var_dump($data);
echo "</pre>";

主要使用array_slice函数

官方描述 Description

array_slice(
    array $array,
    int $offset,
    ?int $length = null,
    bool $preserve_keys = false
): array

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

参数

array

The input array.

offset

If offset is non-negative, the sequence will start at that offset in the array.

If offset is negative, the sequence will start that far from the end of the array.

Note:

The offset parameter denotes the position in the array, not the key.

length

If length is given and is positive, then the sequence will have up to that many elements in it.

If the array is shorter than the length, then only the available array elements will be present.

If length is given and is negative then the sequence will stop that many elements from the end of the array.

If it is omitted, then the sequence will have everything from offset up until the end of the array.

preserve_keys

Note:

array_slice() will reorder and reset the integer array indices by default. This behaviour can be changed by setting preserve_keys to true. String keys are always preserved, regardless of this parameter.

咻兔哔
咻兔哔·2021年11月29日

本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处

推荐文章

Gorm格式化时间输出的另一种实现
后端技术

Gorm格式化时间输出的另一种实现

本文介绍了使用Gorm库处理时间字段的方法。首先,通过定义一个自定义结构体`UseDateTime`和`UseSoftDelete`来存储时间信息,并利用Gorm的hooks在数据库操作后进行时间格式化输出。具体实现包括在`AfterFind`方法中对时间字段进行格式化输出,以及在删除操作后更新时间字段为删除时间。最终,通过JSON格式返回数据,确保时间信息的正确显示。这种方法虽然简单,但能有效地解决Gorm读取时间带有时区的问题,同时避免了使用自定义类型带来的复杂性。

7月22日5
Golang三方库收集-不定期更新
后端技术

Golang三方库收集-不定期更新

以下是一些热门的第三方库,包括网络请求库、RPC库、Web框架、热重启库、定时任务库、获取机器状态库、JWT库、验证码库、邮件库、汉字转拼音库、消息队列库、随机数库、Redis客户端库、雪花 ID 生成器库、Excel处理库、WEB框架库、数据库库、配置库、REDIS库、工具包库、参数验证库、日志库、JSON库、协程池库和类型转换库。这些库各有特色,适用于不同的开发场景,值得一试。

7月28日2
laravel代码整洁之道
后端技术

laravel代码整洁之道

2月10日2
MySQL 开发规范(转)
后端技术

MySQL 开发规范(转)

数据库对象命名规范 1. 数据库名称:使用代码应用 2. 表名称:使用t开头,如tusereduinfo、tusereduinfo_view等。 3. 字段名称:使用f开头,如fuserid、fusername等。 4. 索引名称:使用i开头,如iuniuid、icreatetime等。 5. 视图名称:使用v开头,如vusereduinfo、vusereduinfo_view等。 6. 存储过程名称:使用sp开头,如spcheckusereduinfo、spgetusereduinfo等。 7. 函数名称:使用func开头,如funcgetuserid、funccheckuserid等。 8. 触发器名称:使用trig开头,如trigcheckusereduinfo、triggetusereduinfo等。 9. 约束命名:使用uk开头,如ukuniqueuserid、ukdefaultrule等。 10. 用户命名:使用user开头,如useradmin、userread应用等。

1月21日1