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 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)