如何使用PHP将数组从一个数组拆分为两个变量

时间:2011-05-14 17:30:19

标签: 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)  
    echo '<a href="/'. $item .'/index.php">'. $item .'</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
Games
Toys
Sports
Fishing
Pools
Boats

现在,我的问题是,如果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

我想知道脚本中要改变什么,所以我基本上可以这样做:

foreach($pagedData AS $item1 and $item2)  
    echo '<a href="'. $item2 .'">'. $item1 .'</a><br>';

1 个答案:

答案 0 :(得分:3)

尝试:

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