Home > Software engineering >  How to add a ascending and descending button to sort a multidimensional array
How to add a ascending and descending button to sort a multidimensional array

Time:03-07

I want to write a code in php which will sort the nilai_pengetahuan on my array in a txt file in ascending and descending order on clicking the respective buttons.

My Array

[
    {"nama":"Ryan","nilai_pengetahuan":"23","nilai_keterampilan":"76"},
    {"nama":"Hary","nilai_pengetahuan":"98","nilai_keterampilan":"89"},
    {"nama":"Ahmad","nilai_pengetahuan":"88","nilai_keterampilan":"77"},
    {"nama":"Rudi","nilai_pengetahuan":"69","nilai_keterampilan":"67"},
    {"nama":"Michi","nilai_pengetahuan":"23","nilai_keterampilan":"32"}
]

My code so far

<Input type="submit" name="asc" value="Ascending" ></Input>
<Input type="submit" name="desc" value="Descending" ></Input>
<?php 
$nilai = json_decode(file_get_contents('array.txt'), true);

foreach ($nilai as $value) {;

    echo "<tr>";
    echo "<td>". $value['nama']; echo"</td>";
    echo "<td>". $value['nilai_pengetahuan']; echo"</td>";
    echo "<td>". $value['nilai_keterampilan']; echo"</td>";
    echo "</tr>";
    } 


if (isset ($_POST ["asc"])){
  usort($nilai, function($a, $b) {
    return $a['nilai_pengetahuan'] <=> $b['nilai_pengetahuan'];
});
}
    
if (isset ($_POST ["desc"])){
  usort($nilai, function($a, $b) {
    return $b['nilai_pengetahuan'] <=> $a['nilai_pengetahuan'];
});
 }
      ?>

CodePudding user response:

Use foreach after conditions :

$nilai = json_decode(file_get_contents('array.txt'), true);

if (isset ($_POST["asc"])){
    usort($nilai, function($a, $b) {
        return $a['nilai_pengetahuan'] <=> $b['nilai_pengetahuan'];
    });
}

if (isset ($_POST["desc"])){
    usort($nilai, function($a, $b) {
        return $b['nilai_pengetahuan'] <=> $a['nilai_pengetahuan'];
    });
}

foreach ($nilai as $value) {
    ...
}
  • Related