[PHP]Write a simple paging static interface and deploy it to Nginx using Pagoda

Use the get method to pass in the page and pageSize parameters, and the interface performs paging processing based on the parameters.

1. Create a PHP file

For example, city.php is used to define the interface and return JSON data.

2. Write the interface in the city.php file

<?php

// 设置响应内容为 JSON 格式
header('Content-Type: application/json');

// 获取传入的参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1; // 当前页码,默认为第一页
$pageSize = isset($_GET['pageSize']) ? intval($_GET['pageSize']) : 10; // 每页数据条数,默认为 10

// 模拟一个数据列表
$dataList = [];
for ($i = 1; $i <= 110; $i++) {
    $city = [
        'id' => $i,
        'name' => 'City ' . $i,
        'code' => 'CODE' . $i
    ];
    array_push($dataList, $city);
}

// 计算总数据条数和总页数
$totalItems = count($dataList);
$totalPages = ceil($totalItems / $pageSize);

// 对页码进行有效性检查
$page = max(min($page, $totalPages), 1);

// 计算当前页的数据起止索引
$startIndex = ($page - 1) * $pageSize;
$endIndex = min($startIndex + $pageSize - 1, $totalItems - 1);

// 提取当前页的数据
$pagedData = array_slice($dataList, $startIndex, $pageSize);

// 构建要返回的数据
$response = [
    'page' => $page,
    'pageSize' => $pageSize,
    'totalPages' => $totalPages,
    'totalItems' => $totalItems,
    'data' => array_map(function ($item) {
        return $item;
    }, $pagedData)
];

// 将数据转换为 JSON 字符串
$json = json_encode($response);

// 输出 JSON 字符串
echo $json;

3. Access interface

1). Access the interface on this machine

2). Use domain name to access from external network

Copy city.php to the site configured by the ECS server

To purchase ECS and use Pagoda to deploy LNMP, you can read another website building process .

Guess you like

Origin blog.csdn.net/u012881779/article/details/134453039