Create a PHP array from a variable and organize decreasingly

Asked

Viewed 40 times

-1

Good afternoon, I’m doing a school project, and I need to display the machines and the number of problems they gave, I would like to show you in a decreasing way.

But after taking a look, I thought it best to create a more organized array with this information so that it looks like this:

array(
'Retro Escavadeira' => 5,
'Cavadeira' => 2,
'Pa' => 3
);

And after that, try to organize the array downwards and display in html table form.

At the moment I am already displaying in table form, but the items are not in descending form, I will post my code as is:

<?php
$arquivo = file("arquivos/etiqueta.txt");

foreach ($arquivo as $imprime) {
    print_r($imprime);
}

$arquivo = 'arquivos/etiqueta.txt';

$nomedasmaquinas = 'arquivos/nomedasmaquinas.txt';

$handle = fopen( $arquivo, 'r' );

$handle2 = fopen( $nomedasmaquinas, 'r' );

$ler = fread( $handle, filesize($arquivo) );
$ler2 = fread( $handle2, filesize($nomedasmaquinas) );

$procurar = $ler; //Esta vindo de um arquivo que contem as informacoes das maquinas, como um texto longo (EX: Nome da maquina: Cavadeira Linha: 1 Gravidade: Media etc...)
$nome_das_maquinas_str = $ler2; //Esta vindo de um arquivo, e as palavras estão separadas por . Ex(Cavadeira, Cavadeira, RetroEscavadeira)

$array = explode('.', "$nome_das_maquinas_str"); //Separo as palavras por . e gravo no array
$array_nomes = array_values(array_unique($array));
$array_count = array_count_values($array);
?>

<table>
<?php
echo "<table>";
//Bloco Das maquinas com problemas
$i = 0;
for($i = 0; $i <= count($array_count) - 2; $i++){ //Ao invés de exibir, eu queria criar um array como exibido acima e depois printar de forma organizada.
    echo "<tr>";
    echo "<td>" . $array_nomes[$i] . "</td>". 
    "<td>". $array_count[$array_nomes[$i]] . "</td>";
}

echo "</table>"
?>
</table>

<?php
// Fecha o arquivo
fclose($handle);
fclose($handle2);
?>

Someone can help me?

Thank you!

  • If you wish to display in alphabetical order, I recommend ksort https://www.php.net/manual/en/function.ksort.php

1 answer

0

In PHP we have the following functions:

  • sort => sorts the array by its value
  • rsort => sorts the array, in reverse order by its value and does not keep the index association
  • asort => sort the array by value keeping index association, for reverse order use arsort

So you want to sort by value use the function arsort. Mode of use:

$a = array( 'a' => 1, 'c' => 4, 'b' => 3);
arsort($a);

Upshot:

'c' => 4,
'b' => 3,
'a' => 1

Then just present the data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.