Advertisement
Guest User

Problem4-Softuni Students

a guest
Aug 31st, 2014
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.00 KB | None | 0 0
  1. <?php
  2.  
  3. $sortColumn = $_GET['column'];
  4. $order = $_GET['order'];
  5.  
  6. $students = [];
  7. $count = 1; //count is the id number. Start at 1. Cannot use array key for ID because of empty lines
  8.  
  9. foreach(explode("\n", $_GET['students']) as $key=>$line) {
  10.     $line = trim($line);
  11.     if (strlen($line) > 0) {
  12.         $data = explode(',', $line); // split the comma separated data
  13.         $students[$key]['id'] = (int)$count;
  14.         $students[$key]['username'] = trim($data[0]);
  15.         $students[$key]['email'] = trim($data[1]);
  16.         $students[$key]['type'] = trim($data[2]);
  17.         $students[$key]['result'] = (int)trim($data[3]);
  18.         $count++;// increase ID
  19.     }
  20.  
  21. }
  22.  
  23.  
  24. //sort via array_multisort helper function
  25. if ($order == 'descending') $sorted = array_orderby($students, $sortColumn , SORT_DESC, 'id', SORT_DESC);
  26. else if ($order == 'ascending') $sorted = array_orderby($students, $sortColumn , SORT_ASC, 'id', SORT_ASC);
  27.  
  28.  
  29.  
  30. //print
  31. echo "<table><thead><tr><th>Id</th><th>Username</th><th>Email</th><th>Type</th><th>Result</th></tr></thead>";
  32. foreach ($sorted as $student){
  33.     echo "<tr>";
  34.     echo "<td>".htmlspecialchars($student['id'])."</td>";
  35.     echo "<td>".htmlspecialchars($student['username'])."</td>";
  36.     echo "<td>".htmlspecialchars($student['email'])."</td>";
  37.     echo "<td>".htmlspecialchars($student['type'])."</td>";
  38.     echo "<td>".htmlspecialchars($student['result'])."</td>";
  39.     echo "</tr>";
  40. }
  41. echo "</table>";
  42.  
  43.  
  44. // thank you jimpoz from array_multisort comment section php.net
  45. // http://php.net/manual/en/function.array-multisort.php#100534
  46. function array_orderby()
  47. {
  48.     $args = func_get_args();
  49.     $data = array_shift($args);
  50.     foreach ($args as $n => $field) {
  51.         if (is_string($field)) {
  52.             $tmp = array();
  53.             foreach ($data as $key => $row)
  54.                 $tmp[$key] = $row[$field];
  55.             $args[$n] = $tmp;
  56.         }
  57.     }
  58.     $args[] = &$data;
  59.     call_user_func_array('array_multisort', $args);
  60.     return array_pop($args);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement