Sort from highest to lowest - PHP

0

I am creating a section for sponsored servers and I would like to create the following: A table, showing the sponsored servers, which should be classified from highest to lowest in a table. They will be classified depending on the number of votes each one has, and the first one that appears in the table must have the <tr class="success"> tag, while the others must have the <tr> tag.

The sponsored-servers.json file stores 3 sponsored servers in JSON format. The all-servers-json file contains many more servers including the sponsored servers, and for each one there is a VOTOS key that contains an integer number of server votes. Sponsored servers must be organized from highest to lowest thanks to the number of votes of each .

I tried using the following PHP code:

<?php foreach(json_decode(file_get_contents('servidores-patrocinados.json')) as $servidor_patrocinado) {
if(!max((arsort(json_decode(file_get_contents('todos-los-servidores.json')))['VOTOS'] == $servidor_patrocinado)) continue; //Continuar al siguiente foreach, el primero necesita ser el con más votos
}
?>

And it has not worked for me.

File structure

servers-sponsored.json :

[
    {
        "NAME": "Aphmau Craft",
        "MCPE_LIST": "minecraftpocket-servers.com",
        "ALIAS": "Aphmau"
    },
    {
        "NAME": "CCPvP",
        "MCPE_LIST": "minecraftpocket-servers.com",
        "ALIAS": "Vote"
    },
    {
        "NAME": "OPMCPE",
        "MCPE_LIST": "minecraftpocket-servers.com",
        "ALIAS": "r8i5"
    }
]

all-the-servers.json : (There are many more):

[
    {
        "MCPE_LIST": "minecraftpocket-servers.com",
        "URL": "https:\/\/minecraftpocket-servers.com\/server\/62849\/vote\/",
        "PREMIUM": false,
        "ALIAS": "5hv7",
        "VOTES": 6,
        "SERVER_NAME": "DateCraftRP",
        "PASSWORD": "$2y$10$UVFMjTy4EtlkN3NFpFhRHOis..EKk5mg5GfpCkcDzO5EERh0kQ3jq"
    },
    {
        "MCPE_LIST": "minecraftpocket-servers.com",
        "URL": "https:\/\/minecraftpocket-servers.com\/server\/64455\/",
        "PREMIUM": false,
        "ALIAS": "Aphmau",
        "VOTES": 284,
        "SERVER_NAME": "Aphmau Craft!",
        "PASSWORD": "$2y$10$xsjwMaheRlfhx.5MXOdFPOJLmEIPlCi12ONWQIXrjxtVVlkW5LYRC"
    },
    {
        "MCPE_LIST": "minecraftpocket-servers.com",
        "URL": "https:\/\/minecraftpocket-servers.com\/server\/49063",
        "PREMIUM": false,
        "ALIAS": "Ashcraft",
        "VOTES": 0,
        "SERVER_NAME": "AshcraftPE",
        "PASSWORD": "$2y$10$1K2o79HQ52dDs\/KxZ1kH0.ogTWyRZvBa02qg5DgqNlfZmfQhMGr8m"
    }
]

By the way, the ALIAS is used to differentiate one server from another.

    
asked by Jorge Salas 29.07.2017 в 16:54
source

1 answer

0

How to create the table with the sponsoring servers sorted according to the amount of votes ascending?

First let's use function file_get_contents to get the contents of the file json and store the string in variable $jsonP .

$jsonP = file_get_contents('servidores-patrocinados.json');
$jsonS = file_get_contents('todos-los-servidores.json');

Then using the json_decode function the JSON string is decoded and the convert to a variable of PHP .

$patrocinados = json_decode($jsonP, true);
$servidores = json_decode($jsonS, true);

We go through the $patrocinados arrangement, in each iteration the $servidores array is searched to find if there are two servers with the same alias, in case that is the element of the $servidores is added (it is the has the votes) to the $servers arrangement.

foreach ($patrocinados as $patrocinado) {
    foreach ($servidores as $servidor) {
        if ($servidor["ALIAS"] == $patrocinado["ALIAS"]) {
            $servers[] = $servidor;
        }
    }
}

Since we already have the variable $servers that contains a two-dimensional array with the sponsored servers and the votes of each of them, what we still have to do is sort it using the function usort that receives two parameters, the first parameter is an array and the second is a function that defines how the array should be sorted. The function compares whether the votes ( $a["VOTES"] ) of one element is less than those of another ( $b["VOTES"] ), if the condition is met returns 1 but returns -1 .

This syntax condición ? verdadero : falso is of the ternary operator, the same can be done by the control statement if , that is, if (condicion) {verdadero} else {falso} .

usort($servers, function($a, $b) {
    return $a["VOTES"] < $b["VOTES"] ? 1 : -1;
});
?>

At this moment the arrangement is sorted and we only have to go through it to add the rows ( <tr> ) to the table ( <table> ).

<table>
    <thead>
        <tr>
            <th>Nombre</th>
            <th>Votos</th>
        </tr>
    </thead>
    <tbody id="servidores">
        <?php foreach ($servers as $servidor) { ?>
            <!-- Se podría agregar un if que compruebe si es la primera fila 
            (es decir, si el indice es igual a 0) para colocar la clase "success", 
            pero no es muy elegante -->
            <tr>
                <td><?php echo $servidor["SERVER_NAME"] ?></td>
                <td><?php echo $servidor["VOTES"] ?></td>
            </tr>
        <?php } ?>
    </tbody>
</table>

How to add the class success to the first row of the table?

First you have to select the first child ( <tr> ) of the <tbody> using the property firstChildElement .

var primeraFila = document.getElementById('servidores').firstElementChild;

Then the class success is added modifying the property classList .

primeraFila.classList.add('success');

Full code

<?php

$jsonP = file_get_contents('servidores-patrocinados.json');
$patrocinados = json_decode($jsonP, true);

$jsonS = file_get_contents('todos-los-servidores.json');
$servidores = json_decode($jsonS, true);

foreach ($patrocinados as $patrocinado) {
    foreach ($servidores as $servidor) {
        if ($servidor["ALIAS"] == $patrocinado["ALIAS"]) {
            $servers[] = $servidor;
        }
    }
}

usort($servers, function($a, $b) {
    return $a["VOTES"] < $b["VOTES"] ? 1 : -1;
});
?>

var primeraFila = document.getElementById('servidores').firstElementChild;
primeraFila.classList.add('success');
.success {
  background-color: green;
}
<table>
    <thead>
        <tr>
            <th>Nombre</th>
            <th>Votos</th>
        </tr>
    </thead>
    <tbody id="servidores">
        <?php foreach ($servers as $servidor) { ?>
            <tr>
                <td><?php echo $servidor["SERVER_NAME"] ?></td>
                <td><?php echo $servidor["VOTES"] ?></td>
            </tr>
        <?php } ?>
    </tbody>
</table>
    
answered by 29.07.2017 / 18:07
source