Не могу упорядочить таблицу в html по алфавиту первого столбца

есть код:

<?php
function address($UID){
  $con = [
    "ip" => "********",
    "user" => "*****",
    "password" => "********",
    "db" => "*******",
  ];

  $fs = mysqli_connect($con["ip"], $con["user"], $con["password"], $con["db"]);
  $sql = 'SELECT * FROM Subdivision';
  $result = mysqli_query($fs, $sql);
  mysqli_set_charset($fs, "utf8");

  while ($row = mysqli_fetch_array($result)) {
      #print($row['CodeSub'].$row['Subdivision']."<br>");
  };


  $params = array("action" => "getAddressByID", "UID_dom" => $UID);
  $json = http_build_query($params);

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "http://192.168.250.61/SMD_server/MAIN.php");
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "cache-control: no-cache",
    "content-type: application/x-www-form-urlencoded",
  ));
  $response = curl_exec($ch);
  curl_close($ch);
  $json = json_decode($response);

  foreach ($json as $key => $value){
      if ($key == 'DATA'){
          foreach ($value as $key => $value)
              print $value;
              return $value;
      };
  };
};





if ((isset($_POST['date_from'])) and (isset($_POST['date_to']))) {
  $date_from = $_POST['date_from'];
  $date_to = $_POST['date_to'];
  if (($date_from == '') or ($date_to == ''))
    echo "Заполните все поля";
  
  else{

    // Данные для отправки
    $request = array(
      "Date1"=>$date_from,
      "Date2"=>$date_to,
      "action"=>"dateMonitoring"
    );

    // Указание опций для контекста потока
    $options = array (
      'http' => array (
          'method' => 'POST',
          'header' => "Content-Type: application/json; charset=utf-8\r\n",
          'content' => json_encode($request)
      )
    );

    // Создание контекста потока
    $context = stream_context_create($options);
    // Отправка данных и получение результата
    $connect = file_get_contents('http://198.169.250.62:8645', 0, $context);
    
    
    
    
    $json = json_decode($connect, true);
    
    echo '<table class="report" id="myTable">';
    echo '<thead><tr>
        <th rowspan="3">Адрес</th> <th rowspan="3">ID устройства</th> <th rowspan="3">Кол-во событий</th> <th colspan="6">Успешных событий</th> <th colspan="2" rowspan = "2">Кол-во неуспешных событий</th> 
        </tr>
        <tr>
        <th colspan="2">Первичных</th>  <th colspan="2">Повторных</th>   <th colspan="2">Всего</th>  
        </tr>
        <tr>
        <th>Кол-во</th><th>%</th>   <th>Кол-во</th><th>%</th> <th>Кол-во</th><th>%</th> <th>Кол-во</th><th>%</th>
        </tr></thead>
        <tbody>';
        
    $i = 1;
    $number_of_events = 0;
    $number_of_events_primary = 0;
    $number_of_events_repeated = 0;
    $number_of_events_successfulle = 0;
    foreach ($json as $key => $value) {

      if (strpos($key, 'Data') !== false){ 
        $number_of_events += $value["all_events"];
        $number_of_events_primary += (int)$value["successfully"];
        $number_of_events_repeated += (int)$value["repeated"];
        $number_of_events_successfulle += $all_successfully;
        $UID = str_replace("smd/", "",$value["id"]);
        $primary_events = round((int)$value["successfully"]/(int)$value["all_events"]*100,2);
        $repeated_events = round((int)$value["repeated"]/(int)$value["all_events"]*100,2);
        $all_successfully = ((int)$value["successfully"]+(int)$value["repeated"]);
        $unsuccessful_events = ((int)$value["all_events"]-(int)$value["successfully"]-(int)$value["repeated"]);
        $percent_all_successfully = round($all_successfully/(int)$value["all_events"]*100,2);
        if ($percent_all_successfully < 50)
          echo '<tr bgcolor = "#F08080">';
        elseif (($percent_all_successfully > 50) and ($percent_all_successfully <98))
          echo '<tr bgcolor = "#F0E68C">';
        else
          echo '<tr>';
        echo  
              '<td>'.address($UID).'</td> 
              <td>'.$UID.'</td>
              <td>'.$value["all_events"].'</td>
              <td>'.$value["successfully"].'</td>
              <td>'.$primary_events.'</td>
              <td>'.$value["repeated"].'</td> <td>'.$repeated_events.'</td>
              <td>'.$all_successfully.'</td>
              <td>'.$percent_all_successfully.'</td>
              <td>'.$unsuccessful_events.'</td>
              <td>'.round($unsuccessful_events/(int)$value["all_events"]*100,2).'</td> 
              
             </tr>';
      }
      //<td><br><input type="button" name="'.$UID.'" id="comment" value="Добавить коментарий"></td>
      $i+=1;
    }
    $number_of_all_unsuccessfull = $number_of_events-$number_of_events_primary-$number_of_events_repeated;
    echo '<tr><th colspan = "3">Итого</th>
    <th>'.$number_of_events.'</th>
    <th>'.$number_of_events_primary.'</th>
    <th>'.round($number_of_events_primary/$number_of_events*100,2).'</th>
    <th>'.$number_of_events_repeated.'</th>
    <th>'.round($number_of_events_repeated/$number_of_events*100,2).'</th>
    <th>'.$number_of_events_successfulle.'</th>
    <th>'.round($number_of_events_successfulle/$number_of_events*100,2).'</th>
    <th>'.$number_of_all_unsuccessfull.'</th>
    <th>'.round($number_of_all_unsuccessfull/$number_of_events*100,2).'</th>
    </tr>';*/
    echo '</tbody>';
    echo '</table>';
  }
}

?>

Он выводит таблицу, с этим проблем нет. Первый столбик "Адрес" нужно упорядочить в алфавитном порядке. Находила много примеров кода, но ни один из них не сработал... Что я делаю не так? Я добавляю эту кнопку перед таблицей:

<p><button onclick="sortTable()">Sort</button></p>

И js в самом конце:

<script>
function sortTable() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
  switching = true;
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.getElementsByTagName("TR");
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 1].getElementsByTagName("TD")[0];
      //check if the two rows should switch place:
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        //if so, mark as a switch and break the loop:
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
  }
}
</script>

Ответы (1 шт):

Автор решения: Zhihar
  1. почему бы просто на уровне php уже не отсортировать массив $json по полю $id, вернее превратив при проверке в str_replace("smd/", "",$value["id"]);?

     function sort_by_address($a, $b) {
         $val1 = str_replace("smd/", "",$a["id"]);
         $val2 = str_replace("smd/", "",$a["id"]);
    
         return strcmp($val1, $val2);
    
         // или если требуется только -1, 0, 1
         $res = strcmp($val1, $val2);
    
         return $res < 0 ? -1 : ($res > 0 ? 1 : 0)
     }
    
     usort($json, "sort_by_address");
    
  2. почему бы не воспользоваться внешней библиотекой, которая позволяет сортировать уже готовые таблицы по любым столбцах, к примеру https://www.jqueryscript.net/tags.php?/table%20sort/ и не забивать тогда голову лишним кодингом

→ Ссылка