如何使用PHP将数字分配给数组中的一行

时间:2011-05-17 05:58:43

标签: php

以下是我现在使用的脚本:

<?php 
echo '<html><body>';

// Data from a flat file  
$dataArray = file('text.dat');

// Get the current page  
if (isset($_REQUEST['page'])) {
    $currentPage = $_REQUEST['page'];
} else {
    $currentPage = 'some default value';
}

// Pagination settings  
$perPage = 3;  
$numPages = ceil(count($dataArray) / $perPage);  
if(!$currentPage || $currentPage > $numPages)  
    $currentPage = 0;  
$start = $currentPage * $perPage;  
$end = ($currentPage * $perPage) + $perPage;

// Extract ones we need  
foreach($dataArray AS $key => $val)  
{  
    if($key >= $start && $key < $end)  
        $pagedData[] = $dataArray[$key];  
}

foreach($pagedData AS $item) {  
    $item = explode('||', $item);
    echo '<a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}

if($currentPage > 0 && $currentPage < $numPages)  
    echo '<a href="?page=' . ($currentPage - 1) . '">« Previous page</a><br>';  
if($numPages > $currentPage && ($currentPage + 1) < $numPages)  
    echo '<a href="?page=' . ($currentPage + 1) . '" class="right">Next page »</a><br>';

echo '</body></html>';
?>

这是text.dat

的内容
Fun||http://site.com/page11.html
Games||http://site.com/page12.html
Toys||http://site.com/page13.html
Sports||http://site.com/page16.html
Fishing||http://site.com/page18.html
Pools||http://site.com/page41.html
Boats||http://site.com/page91.html

这是我的问题。这个数组中有七行。如何在显示的链接旁边显示行号(我认为是$ key)?我应该最终得到一个链接列表,每个链接都有自己的编号,如:

LINE NUMBER - <a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br />

感谢您的帮助......

2 个答案:

答案 0 :(得分:2)

您需要一个计数器变量,如$i,它在循环中递增。

$i = $start;
foreach ($pagedData as $item) {
    $item = explode('||', $item);
    echo $i. ' - <a href ...';
    $i++;
}

修改$i开始$start,因此它与$key的编号相匹配。

答案 1 :(得分:1)

我假设你想要文件中的行号而不是输出的行号。如果是这样,那么改变这个:

// Extract ones we need  
foreach($dataArray AS $key => $val)  
{  
    if($key >= $start && $key < $end)  
        $pagedData[] = $dataArray[$key];  
}

foreach($pagedData AS $item) {  
    $item = explode('||', $item);
    echo '<a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}

这样的事情:

// Extract ones we need  
foreach($dataArray AS $key => $val)  
{  
    if($key >= $start && $key < $end)  
        $pagedData[$key] = $dataArray[$key];  
}

foreach($pagedData AS $key => $item) {  
    $item = explode('||', $item);
    echo $key+1 . ' - <a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}