回应foreach循环

时间:2012-12-15 00:54:27

标签: php arrays

我有以下代码

 $contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
    $contents = explode("\n", $contents);
    foreach ($contents as $key => $itemline)


    {
    }


    foreach ($fnamearray as $key2 => $fname)
    {

    echo ($fname);
    echo ($itemline);
    }

我想要做的是让每个文件的第一行回显,使输出看起来像

FNAME [0},itemline [0],FNAME [1],itemline [1]

我得到的是以下内容就是这样 fname [0],fname [1],fname [2] .... ect

ħ

2 个答案:

答案 0 :(得分:2)

由于两个数组都是简单的连续数字索引数组,因此您只需使用for循环:

$l = max(count($fnamedata),count($contents));
for($i=0; $i<$l; $i++) {
  $itemline = $contents[$i];
  $fname = $fnamearray[$i];
  // do stuff
}

答案 1 :(得分:2)

假设索引始终匹配:

$contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('/home/b1396hos/public_html/ofwgkta.co.uk/dd_folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
$contents = explode("\n", $contents);

for($i = 0; $i < count($contents); $i++)
{
    echo $fnamearray[$i];
    echo $contents[$i];
}