0

Helo guys, i need your help.

I have an arrays data :

   $biodata = array(
            array(
                'nama' => 'Ayu',
                'gender' => 'P',
                'usia' => 12,
            ),
            array(
                'nama' => 'Doni',
                'gender' => 'L',
                'usia' => 30,
            ),
            array(
                'nama' => 'Yasina',
                'gender' => 'P',
                'usia' => 24,
            ),
            array(
                'nama' => 'Irul',
                'gender' => 'L',
                'usia' => 20,
            ),
            array(
                'nama' => 'Abdis',
                'gender' => 'L',
                'usia' => 21,
            ),
    );

I want to sort the data by 'gender' and 'usia', then I have to display it in the html table, what should I do?

here's my code :

usort($biodata, function($a, $b){
    return $a['gender'] > $b['gender'];
});

?>

<table border="1px" width="400px" align="center">
    <tr>
        <td>No</td>
        <td>NAMA</td>
        <td>GENDER</td>
        <td>Usia</td>
    </tr>
<?php 
;   $i = 1;
    foreach ($biodata as $d) {

     ?>
    <tr><td><?php echo $i; ?></td>
        <td><?php echo $d['nama']; ?></td>
        <td><?php echo $d['gender']; ?></td>
        <td><?php echo $d['usia']; ?></td>
    </tr>
    <?php 

    $i = $i +1;

        } ?>
</table>

but it only sorts by gender, what I need is to sort by 'gender' and 'usia'. I really hope to find help here, I'm very curious.

Stev
  • 43
  • 1
  • 4
  • 1
    hi welcome, please also add how you have done so far. – ZarNi Myo Sett Win Mar 10 '20 at 02:14
  • Does this answer your question? [Sort Multidimensional arrays by sub array key value](https://stackoverflow.com/questions/14994075/sort-multidimensional-arrays-by-sub-array-key-value) – vadivel a Mar 10 '20 at 03:30
  • Yes, mate. but what I need is to sort by 'gender' and 'usia', not just one of them. thanks, mate – Stev Mar 10 '20 at 05:10
  • How about this? https://stackoverflow.com/questions/3232965/sort-multidimensional-array-by-multiple-keys – Batu.Khan Mar 10 '20 at 05:55

1 Answers1

0

You can do it in this way

$sortColumn = ['gender', 'usia'];
foreach($sortColumn as $column){
  usort($biodata, function($a, $b) use ($column){
    return $a[$column] > $b[$column];
  });  
}

Demo : https://3v4l.org/bRIMQ

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20