douba3378 2016-05-05 15:45
浏览 68
已采纳

在PHP中对文本文件中的列表重新排序

everyone. Very first question, so take it easy on this noob. ;)

Anyway, really stumped on something. I've got a text file with this sort of listing:

1: A C D
4: A B
5: D F
7: A E
9: B C

The goal is to somehow re-sort this list and have it appear as this:

A: 1 4 7
B: 4 9
C: 1 9
D: 1 5
E: 7
F: 5

The trick is matching and displaying those matched values. For example "A" is matched with lines 1,4 and 7, and so on. I can explode the lines into individual arrays, but after that stumps me. How would I go about taking those arrays and somehow sorting them out to make it look like the final version?

Thanks for any and all info!

UPDATE:

Code I have so far:

<?php
$string="1: A C D
4: A B
5: D F
7: A E
9: B C";
$lines = explode( "
", $string );
sort($lines);
foreach($lines as $line){
echo $line."<br>";
}

// start with this
//1: A C D
//4: A B
//5: D F
//7: A E
//9: B C

// resort and display as this
//A: 1 4 7
//B: 4 9
//C: 1 9
//D: 1 5
//E: 7
//F: 5
?>

Which produces:

1: A C D
4: A B
5: D F
7: A E
9: B C

Right now I don't care that they are not in new lines. That's not important at the moment. Right now, I need to figure out how to make it sort and appear as the 2nd code block. That is the part that puzzles me.

Hope this helps clear up things.

  • 写回答

4条回答 默认 最新

  • doudi2833 2016-05-05 17:30
    关注

    Well, you sort of gave it a try and I was bored:

    //read file into array of lines
    $lines = file('/path/to/file.txt', FILE_IGNORE_NEW_LINES);
    
    //loop through the lines
    foreach($lines as $line) {
        //explode on space
        $cols = explode(' ', $line);
        //loop through columns and build array with letter as key adding number to that array
        for($i=1; $i < count($cols); $i++) {
            $result[$cols[$i]][] = trim($cols[0], ':');
        }
    }
    //sort by key (or sort $output later)
    ksort($result);
    
    //loop through and build new lines
    foreach($result as $key => $vals) {
        $output[] = "{$key}: " . implode(' ', $vals);
    }
    //write lines to file
    file_put_contents('/path/to/file.txt', implode("
    ", $output));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?