php как связать значения двух массивов друг с другом - PullRequest
1 голос
/ 25 мая 2020

Для блога с плоскими файлами я читаю все файлы блога (файлы .txt) с помощью glob. Каждый файл .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




1 Ответ

1 голос
/ 25 мая 2020

Он хранит похожие, немного отличающиеся друг от друга, использует заголовок в качестве индекса массива лайков, строит список всех файлов и затем сортирует список в обратном порядке (поддерживая индекс с использованием 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...