Advertisement
Guest User

softuniTunes

a guest
Sep 2nd, 2014
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 0 0
  1. <?php
  2. $lines = $_GET['text'];
  3. $property = $_GET['property'];
  4. $artistInput = $_GET['artist'];
  5. $order = $_GET['order'];
  6.  
  7. preg_match_all('/^.*$/m', $lines, $matches);
  8. $linesArr = array();
  9.  
  10. for ($i = 0; $i < count($matches[0]); $i++) {
  11.     $songInfo = explode(" | ", $matches[0][$i]);
  12.     $linesArr[] = [
  13.         'name' => $songInfo[0],
  14.         'genre' => $songInfo[1],
  15.         'artist' => explode(", ", $songInfo[2]),
  16.         'downloads' => (int)$songInfo[3],
  17.         'rating' => floatval($songInfo[4])
  18.     ];
  19. }
  20.  
  21. //sort the names of the artists on each line
  22.  
  23. $sortedArtistNames = [];
  24. foreach ($linesArr as $line) {
  25.     asort($line['artist']);
  26.     $line['artist'] = implode(", ", $line['artist']);
  27.     $sortedArtistNames[] = $line;
  28. }
  29.  
  30. //make a new array with only the lines that contain the name of the selected artist
  31.  
  32. $artistChosen = [];
  33. foreach ($sortedArtistNames as $line) {
  34.     foreach ($line as $key => $value) {
  35.         if (strpos($value, $artistInput) !== false) {
  36.             $artistChosen[] = $line;
  37.         }
  38.     }
  39. }
  40.  
  41. //sort the lines by the given property
  42.  
  43. usort($artistChosen, function($s1, $s2) use ($order, $property) {
  44.     if ($s1[$property] == $s2[$property]) {
  45.         return strcmp($s1['name'], $s2['name']);
  46.     }
  47.     return ($order == "ascending" ^ $s1[$property] < $s2[$property]) ? 1 : -1;
  48. });
  49.  
  50. //print the result
  51.  
  52. $output = "<table>\n<tr><th>Name</th><th>Genre</th><th>Artists</th><th>Downloads</th><th>Rating</th></tr>\n";
  53.  
  54. for ($i = 0; $i < count($artistChosen); $i++) {
  55.     $name = htmlspecialchars($artistChosen[$i]['name']);
  56.     $genre = htmlspecialchars($artistChosen[$i]['genre']);
  57.     $artist = htmlspecialchars($artistChosen[$i]['artist']);
  58.     $downloads = $artistChosen[$i]['downloads'];
  59.     $rating = $artistChosen[$i]['rating'];
  60.     $output .= "<tr><td>$name</td><td>$genre</td><td>$artist</td><td>$downloads</td><td>$rating</td></tr>\n";
  61. }
  62.  
  63. $output .= "</table>";
  64. echo $output;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement