萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 取模運算符 (%) 實戰技巧:分頁、分組、輪詢、負載均衡

取模運算基礎

$a % $b  // 返回 $a 除以 $b 的餘數
// 性質:0 <= 結果 < |$b| (PHP 中結果符號同被除數)

高頻實戰場景

1. 表格/列表分行、分組渲染

<?php
$items = range(1, 20); // 20 個項目
$cols = 4;             // 每行 4 列

echo "<table><tr>";
foreach ($items as $index => $item) {
    // 每行首列輸出 
    if ($index % $cols === 0) {
        if ($index > 0) echo "</tr>";
        echo "<tr>";
    }
    echo "<td>項目 $item</td>";
}
// 補齊最後一行
$remainder = count($items) % $cols;
if ($remainder !== 0) {
    echo str_repeat("<td>&nbsp;</td>", $cols - $remainder);
}
echo "</tr></table>";

2. 分頁導航:顯示當前頁附近頁碼

<?php
function pagination(int $currentPage, int $totalPages, int $window = 2): array
{
    $pages = [];
    $start = max(1, $currentPage - $window);
    $end = min($totalPages, $currentPage + $window);
    
    for ($i = $start; $i <= $end; $i++) {
        $pages[] = $i;
    }
    return $pages;
}

// 另一種:固定顯示 10 頁一組
$groupSize = 10;
$currentGroup = (int)(($currentPage - 1) / $groupSize);
$startPage = $currentGroup * $groupSize + 1;
$endPage = min($startPage + $groupSize - 1, $totalPages);

3. 輪詢/輪轉分配 (負載均衡、任務分發)

<?php
$servers = ['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4'];
$requestId = 12345;

// 簡單輪詢
$selected = $servers[$requestId % count($servers)];

// 權重輪詢 (平滑加權)
$weights = [10, 20, 30, 40]; // 權重總和 100
$totalWeight = array_sum($weights);
$point = $requestId % $totalWeight;

$accumulated = 0;
foreach ($servers as $i => $server) {
    $accumulated += $weights[$i];
    if ($point < $accumulated) {
        $selected = $server;
        break;
    }
}

4. 緩存分片 (Redis Cluster、一致性哈希預演)

<?php
$redisNodes = ['redis1:6379', 'redis2:6379', 'redis3:6379'];

function getNode(string $key, array $nodes): string
{
    // 簡單取模分片 (生產建議 CRC32/一致性哈希)
    $hash = crc32($key); // 32 位無符號
    return $nodes[$hash % count($nodes)];
}

$key = "user:12345:profile";
$node = getNode($key, $redisNodes);

5. 批次處理進度條/日誌輸出控制

<?php
$total = 100000;
$batchSize = 500;

for ($i = 0; $i < $total; $i += $batchSize) {
    // 處理批次...
    processBatch($i, $batchSize);
    
    // 每 10 批輸出一次進度 (減少 I/O)
    if (($i / $batchSize) % 10 === 0) {
        $percent = round(($i / $total) * 100, 1);
        echo "進度: {$percent}% ({$i}/{$total})\n";
    }
}

6. 循環數組/環形緩衝區

<?php
$buffer = [null, null, null, null, null]; // 固定大小 5
$capacity = count($buffer);
$head = 0; // 寫入位置
$count = 0; // 當前元素數

function ringPush(array &$buffer, &$head, &$count, $value, int $capacity): void
{
    $buffer[$head] = $value;
    $head = ($head + 1) % $capacity;
    if ($count < $capacity) $count++;
}

function ringGet(array $buffer, int $head, int $count, int $index): mixed
{
    if ($index < 0 || $index >= $count) return null;
    // 邏輯索引 0 = 最舊元素
    $physicalIndex = ($head - $count + $index + $capacity) % $capacity;
    return $buffer[$physicalIndex];
}

7. 判斷奇偶、整除、質數篩選

<?php
// 奇偶
$isEven = ($n % 2 === 0);
$isOdd  = ($n % 2 !== 0);

// 整除檢查 (能被 3 和 5 整除 = FizzBuzz)
if ($n % 15 === 0) echo "FizzBuzz";
elseif ($n % 3 === 0) echo "Fizz";
elseif ($n % 5 === 0) echo "Buzz";

// 簡易質數檢查 (試除法)
function isPrime(int $n): bool
{
    if ($n < 2) return false;
    if ($n % 2 === 0) return $n === 2;
    for ($i = 3; $i * $i <= $n; $i += 2) {
        if ($n % $i === 0) return false;
    }
    return true;
}

負數取模陷阱

<?php
// PHP: 結果符號同被除數 (被除數為負,結果為負)
echo -7 % 3;   // -1 (非 2)
// Python/數學定義: 結果符號同除數 (總是非負)
// 統一為非負餘數函數
function mod(int $a, int $b): int
{
    $r = $a % $b;
    return $r < 0 ? $r + $b : $r;
}
echo mod(-7, 3); // 2

效能微優化

  • 2 的冪次取模:$n % 8 === $n & 7 (位運算更快)
  • 循環中固定除數:編譯器優化常數傳播
  • 避免在極熱路徑使用取模,改用計數器重置

總結

取模運算是將線性序列映射到循環空間的核心工具。掌握「索引 % 周期 = 位置」模式,即可輕鬆處理分頁、分組、輪詢、分片、環形結構等經典問題。注意 PHP 負數取模語義差異,跨語言移植時統一處理。

copyright © 萬盛學電腦網 all rights reserved