PHP循环数组时

时间:2011-09-20 11:20:11

标签: php arrays loops

Hy大家,我在使用正确嵌套while循环从2个数组中读取时遇到了问题。 我有两个文件,我从中读取内容:

file1: item_list.txt
string1 \n
string2 \n
string3 \n
...

file2: item+info.txt
string3 \t info1 \t info2 \t info3
string1 \t info7 \t info1 \t info4
string5 \t info2 \t info3
string2 \t info2 \t info4 \t info1

(值仅由新行和标签分隔,我在字符之间添加了一个空格,以增加可读性)

我使用 fgetcsv()函数从文件中读取文件,文件中的每一行都作为数组存储到变量 $ data 中。我使用条件(!feof($ fp))创建了一个 while 循环来读取文件直到最后一行。但我无法正确嵌套第二个循环。

我想用这个做什么: 读取file1中找到的第一个字符串,转到file2并尝试查找该字符串。如果匹配,请获取该字符串的信息数据(所有数据,或只有一个,无关紧要)。如果没有匹配项,请返回“不匹配”消息。在任何一种情况下,一旦第二个循环完成了它,我需要读取file1中的第二个字符串,然后再次在file2中进行搜索。只要有从文件1中读取的内容,就重复此操作。

这是我的代码的两个版本,它们不起作用,我无法弄清楚为什么。

//opening the files
$fp = fopen("$DOCUMENT_ROOT/test/item_list.txt", "r"); #raw item list
$pf = fopen("$DOCUMENT_ROOT/test/item+info.txt", "r"); #item+info list

//read from first file
$line=0;
while (!feof($fp)){
    $line++;
    $data1 = fgetcsv($fp, "1000", "\n");
    $item1= $data1[0];
    echo "line: $line. item_list: ".$item1; //just to see on screen what's happening
    print_r($data1); //same here, just to see what's going on
    echo"<br />";

    //searching for string in file2
    $row=0;
    while (!feof($pf)){
        $row++;
        $data2 = fgetcsv($pf, "1000", "\t");
        $item2= $data2[0];
        echo "line: $row. item+info: ".$item2; //just checking things on screen
        print_r($data2); //here too
        echo "<br />";

        //conditioning
        //equal strings
        if ($string1== $string2)
            echo $data2[1]."<br />";
        break;
    }
}

fclose($fp);
fclose($pf);

只要item_list.txt和item + info.txt中的项目已经完成,这就可以工作了 完全相同(string1 \ nstring2 \ string3 - &gt;
string1 \ tinfo1 \ nstring2 \ tinfo2 \ nstring3 \ tinfo3 - 但这永远不会发生在我的身上 如果不能订购像那样的物品那么

我尝试使用foreach()语句通过数组进行迭代,但结果是我无法理解的结果。

while (!feof($fp)){
    $data1 = fgetcsv($fp);
    foreach ($data1 as $token1) {
        while (!feof($pf)) {
            $data2 = fgetcsv($pf);
            foreach ($data2 as $value) {
                explode ("\t", $value);
                if ($token1 == $value[0])
                    echo $value[1];
            } 
            break;
        } 
    }
}

3 个答案:

答案 0 :(得分:1)

这应该这样做:

$file1 = file($DOCUMENT_ROOT . '/test/item_list.txt');
$file2 = file($DOCUMENT_ROOT . '/test/item+info.txt');

foreach ($file1 as $line)
{
    $line = rtrim($line); // just in case ...
    if ($line === '') continue;

    foreach($file2 as $infoline)
    {
        $infoline = explode("\t", rtrim($infoline);
        if ($line === $infoline[0])
        {
            array_shift($infoline);
            echo $line . '<br /><br />' . implode('<br />', $infoline);
            // $results[$line] = $infoline; // uncomment this if you need the search results stored for later use
            break;
        }
    }
}

答案 1 :(得分:0)

这是一个粗略的镜头:

$filename1 = 'item_list.txt';
$filename2 = 'item+info.txt';

# Init the Raw Array
$content2raw = array();

# Get the File Contents for File 2
$file2 = file_get_contents( $filename2 );
# Split it into an Array by Line Breaks
$content2raw = preg_split( "/\n/" , $file2 , -1 , PREG_SPLIT_NO_EMPTY );

# Unset the variable holding the file contents
unset( $file2 );

# Init the Fixed Array
$content2 = array();

# Loop through the Raw Array
foreach( $content2raw as $l ){
  // Each Line of Filename2
  # Split the Line on Tabs
  $t = preg_split( "/\s*\t\s*/" , $l , -1 );
  # Set the Fixed Array, using the first element from the line as the key
  $content2[ $t[0] ] = $t;
}

# Unset the Raw Array
unset( $content2raw );

# Get the File Contents from File 1
$file1 = file_get_contents( $filename1 );
# Split it into an Array by Line Breaks
$contents1 = preg_split( "/\n/" , $file1 , -1 , PREG_SPLIT_NO_EMPTY );

# Unset the variable holding the file contents
unset( $file1 );

# Loop through the Lines, using each line as the Key to look for
foreach( $content1 as $v ){
  # Check whether a matching element exists in the array from File 2
  if( !array_key_exists( $k , $content2 ) ){
    // No Match Found
    echo 'No Match';
  }else{
    // Match Found
    echo 'Match Found';
    var_dump( $content2[$v] );
  }
}

修正案,根据@Bluewind的评论/反馈

$filename1 = 'item_list.txt';
$filename2 = 'item+info.txt';

# Open and Split the file into an Array by Line
$content2raw = file( $filename2 );

# Init the Fixed Array
$content2 = array();

# Loop through the Raw Array
foreach( $content2raw as $l ){
  // Each Line of Filename2
  # Split the Line on Tabs
  $t = preg_split( "/\s*\t\s*/" , $l , -1 );
  # Set the Fixed Array, using the first element from the line as the key
  $content2[ $t[0] ] = $t;
}

# Unset the Raw Array
unset( $content2raw );

# Open and Split the file into an Array by Line
$contents1 = file( $filename1 );

# Loop through the Lines, using each line as the Key to look for
foreach( $content1 as $v ){
  # Check whether a matching element exists in the array from File 2
  if( !array_key_exists( $k , $content2 ) ){
    // No Match Found
    echo 'No Match';
  }else{
    // Match Found
    echo 'Match Found';
    var_dump( $content2[$v] );
  }
}

答案 2 :(得分:0)

这实际上比您想象的要少得多。首先,您读取一个info文件并从中构建一个哈希表:

foreach(file("info_list") as $line) {
    $line = explode("\t", trim($line));
    $info[$line[0]] = $line;
}

然后遍历items文件并查看散列中是否有匹配的条目:

foreach(file("item_list") as $line) {
    $item = trim($line);
    if(isset($info[$item]))
        // we have some info for this item 
    else
        // we have no info for this item
}

基本上都是关于这个