【问题标题】:Paginate combination of arrays without generating the whole combination in advance对数组的组合进行分页,而不预先生成整个组合
【发布时间】:2014-10-22 19:12:35
【问题描述】:

我有以下循环组合两个数组并在有序列表中显示结果:

$list1 = array("make","break","buy");
$list2 = array("home","car","bike");

echo "<ol>";
for($a=0; $a<3; $a++){
    for($b=0; $b<3; $b++){
        echo "<li".($list1[$a].$list2[$b])."</li>";
    }
}
echo "</ol>";

我拥有的实际数组每个包含大约 1500 个单词,因此列表长度超过 200 万个。

有没有办法用分页显示结果,而不需要预先生成整个结果集? 例如每页 500 个项目?

仅供参考,我不一定需要在有序列表中显示结果,如果这会打乱分页。

【问题讨论】:

  • “有没有办法通过分页来显示结果?” - 你没有用谷歌搜索过“php 分页”吗?我敢打赌我可以在 5 秒内找到 50 个结果flat 我不会这样做,那是你的工作。
  • @Fred-ii- 我打赌他/她做到了...我做到了,但没有发现与分页数组组合相关的内容。我觉得这很有趣。
  • @Fred-ii-,您根本不想回答我的问题然后发表评论。不要在你没用的 cmets 上浪费大家的时间。
  • @matpop 感谢您的意见。我确实在网上搜索过,但找不到任何接近我要找的东西。我会试一试您的代码,并会提供反馈。
  • @user2171083 您修改后的代码将不起作用,因为它总是从数组的开头开始循环,而不是您必须能够从可变位置开始,基于选择的限制和当前页面(仔细阅读我的答案)。通常,您应该从当前的 http GET 请求参数中提取当前的$page(如果您愿意,还可以提取$limit),因为您通常将页面中的锚点显示到上一页和下一页(这是通常的分页代码,您可以自己找到)。

标签: php arrays pagination


【解决方案1】:

首先,您需要能够从数组中的任意位置开始循环
当然你可以使用for 循环,但我认为while 循环更适合这里。

$length1 = count($list1);
$length2 = count($list2);

//now indexes are initialized to variable values
$a = $var1; //start position $var1 is an integer variable between 0 and ($length1 - 1)
$b = $var2; //start position $var2 is an integer variable between 0 and ($length2 - 1)

while ($a < $length1) {
    while ($b < $length2) {
        echo '<li>', $list1[$a], ' ', $list2[$b], '</li>';
        $b++;
    }
    $b = 0; //reset inner loop each time it ends
    $a++;
}

接下来,如果在组合结束之前达到每页的最大结果数 ($limit),我们需要一种方法来停止两个循环

$length1 = count($list1);
$length2 = count($list2);
$a = $var1;
$b = $var2;

$counter = 0;

while ($a < $length1) {
    while ($b < $length2) {
        echo '<li>', $list1[$a], ' ', $list2[$b], '</li>';

        $counter++;
        if($counter === $limit) break 2;

        $b++;
    }
    $b = 0;
    $a++;
}

最后,我们必须根据当前的$page(从第1页开始)和$limit,找到上面$var1$var2的正确值。这是简单的算术,我不会在这里解释。
把它们放在一起:

$length1 = count($list1);
$length2 = count($list2);

$offset = $limit * ($page - 1);
$a = (int)($offset / $length2);
$b = $offset % $length2;

$counter = 0;
while ($a < $length1) {
    while ($b < $length2) {
        echo '<li>', $list1[$a], ' ', $list2[$b], '</li>';
        $counter++;
        if($counter === $limit) break 2;
        $b++;
    }
    $b = 0;
    $a++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多