【问题标题】:php how to bind values of 2 arrays with each otherphp如何将2个数组的值相互绑定
【发布时间】:2020-05-25 14:28:33
【问题描述】:

对于平面文件博客,我使用 glob 读取所有博客文件(.txt 文件)。 每个.txt 文件都有不同的行。 .txt 文件如下所示:

id_20200514222532 // id line (0 line)
club            
uploads/12.jpg
soccer           // title line (3rd line)
comment goes here 
14 May 2020 22:25 
john              
soccer,barcelona  
194               
4                // likes line (9th line, number of likes)

我想要实现的目标:只输出点赞最多的 5 个标题!

这是我目前所拥有的:

$files = glob("data/articles/*.txt"); // read all files in dir articles
$title_lines = array();
$like_lines = array();
foreach($files as $file) { // Loop the files in the directory
    $lines = file($file, FILE_IGNORE_NEW_LINES);
    $title_lines[] = strtolower($lines[3]); // grab title line  
    $like_lines[] = $lines[9]; // grab like line
    // $title_lines contains all values of the titles
    // $like_lines contains all values of likes

    // output now only the 5 titles with the most likes

}


所以我的输出应该如下所示:

Soccer (4) // 4 likes
Swim   (3) // 3 likes
Baseball (3) // 3 likes
Volleybal (2) // 2 likes
Athletics (1) // 1 like




【问题讨论】:

    标签: php arrays sorting


    【解决方案1】:

    这存储likes略有不同,它使用标题作为likes数组索引,构建所有文件的列表,然后对列表进行反向排序(使用arsort()维护索引)。然后使用array_slice()获得前5名...

    $like_lines = [];
    $files = glob("data/articles/*.txt"); // read all file sin dir articles
    $like_lines = array();
    foreach($files as $file) { // Loop the files in the directory
        $lines = file($file, FILE_IGNORE_NEW_LINES);
        $like_lines[strtolower($lines[3])] = $lines[9]; // grab like line
    }
    // Sort in descending number of likes
    arsort($like_lines);
    // Extract top 5
    $top5 = array_slice($like_lines, 0, 5);
    
    print_r($like_lines);
    

    【讨论】:

    • 太棒了!正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2019-04-19
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多