简体   繁体   English

PHP在遍历数组时

[英]PHP while looping through arrays

Hy everyone, I'm having trouble with properly nesting while loops to read from 2 arrays. 大家好,我在正确嵌套while循环以读取2个数组时遇到麻烦。 I have 2 files from which I read the content: 我有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

(values are separated by new lines and tabs only, I added one space between characters here just to increase readability) . (值仅由新行和制表符分隔,我在此处在字符之间添加了一个空格,只是为了提高可读性)

I read from files using fgetcsv() function, and each row from file is stored as an array into a variable $data . 我使用fgetcsv()函数读取文件,文件中的每一行都作为数组存储在变量$ data中 I created a while loop with condition (!feof($fp)) to read through the file until the last row. 我创建了一个条件为(!feof($ fp))while循环,以读取文件直到最后一行。 But I can't quite properly nest the second loop. 但是我不能完全嵌套第二个循环。

What I want to do with this: read the first string found in file1, go to file2 and try to find that string. 我要做什么:读取file1中找到的第一个字符串,转到file2并尝试找到该字符串。 If there's a match, get the info data for that string (all of the data, or just one, doesn't matter). 如果有匹配项,请获取该字符串的信息数据(所有数据或仅一个数据都无所谓)。 If there's no match, return message "no match". 如果没有匹配项,则返回消息“ no match”。 In either case, once the second loop has done it's thing, I need to read the second string in file1, and do the search in file2 again. 无论哪种情况,第二个循环完成后,我都需要读取file1中的第二个字符串,然后再次在file2中进行搜索。 Repeat this as long as there is something to read from the file1. 只要要从文件1中读取某些内容,就重复此步骤。

here are two versions of my code, they don't work, and I can't figure out why. 这是我的代码的两个版本,它们不起作用,我不知道为什么。

//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);

this used to work as long as the items in item_list.txt and item+info.txt are oredered 只要对item_list.txt和item + info.txt中的项目进行整理,此方法就可以正常工作
exactly the same (string1\\nstring2\\string3 -> 完全相同(string1 \\ nstring2 \\ string3->
string1\\tinfo1\\nstring2\\tinfo2\\nstring3\\tinfo3 - but that's never going to happen in my case, it's impossible to order the items like that) string1 \\ tinfo1 \\ nstring2 \\ tinfo2 \\ nstring3 \\ tinfo3-但就我而言,这永远不会发生,无法订购类似的物品)

I tried to do it with foreach() statement do itterate through arrays, but the result is something that I can't make any sense out of. 我试图用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;
        } 
    }
}

This should do it: 应该这样做:

$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;
        }
    }
}

Here's a rough shot at it: 这是一个大概的镜头:

$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] );
  }
}

Amendment, as per comment/feedback from @Bluewind 根据@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] );
  }
}

This is actually much less code than you seem to think. 实际上,这比您想像的要少得多的代码。 First, you read an info file and build a hash table out of it: 首先,您读取一个信息文件并从中构建一个哈希表:

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

then you iterate through the items file and look if there are matching entries in the hash: 然后您遍历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
}

that's basically all about this 基本上就是这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM