phpasortksort

PHP my_asort() and my_ksort()


I'm working on this problem of sorting in php. I have to write my own sorting functions, using my_asort() and my_ksort() functions that do exactly the same as asort and ksort respectively. However I'm not able to get the correct output (I'm new to php), hence any help on how to correct this, would be greatly appreciated.

This is the code I typed up:

<?php


echo "Original Array<br><br>";
$member = array("Jack" => "55kg", "Bill" => "35kg", "Aaron" => "60kg", "Daniel" => "80kg" );



foreach ($member as $user => $weight) {
echo "$user = $weight <br>";
}

echo "<br><br>";

function my_asort($member)
    {
    $keys=array_keys($member);
    sort($keys);
    foreach($keys as $key)
        {
        $val=$member[$key];
        unset($member[$key]);
        $member[$key]=$val;
        }
    }

echo "Sorted By user <br><br>";
foreach ($member as $user => $weight) {
echo "$user = $weight <br>";
}

echo "<br><br>";

function my_ksort($member)
    {
    $keys=array_keys($member);
    sort($keys);
    foreach($keys as $key)
        {
        $val=$member[$key];
        unset($member[$key]);
        $member[$key]=$val;
        }
    }

echo "Sorted By weight <br><br>";
foreach ($member as $user => $weight) {
echo "$user = $weight <br>";
}

?>

This is what it displays: (It doesn't do any sorting, what am I doing wrong?)

Original Array

Jack = 55kg 
Bill = 35kg 
Aaron = 60kg 
Daniel = 80kg 


Sorted By user 

Jack = 55kg 
Bill = 35kg 
Aaron = 60kg 
Daniel = 80kg 

Sorted By weight 

Jack = 55kg 
Bill = 35kg 
Aaron = 60kg 
Daniel = 80kg

Solution

  • You need to call your functions (or use the code without a function declaration). You just defined them inside your code.

    So if you want to use them, you need to call them and your code will look like:

    <?php
    
    function my_ksort(&$member)
    {
      $keys=array_keys($member);
      sort($keys);
      foreach($keys as $key)
      {
        $val=$member[$key];
        unset($member[$key]);
        $member[$key]=$val;
      }
    }
    
    function my_asort(&$member)
    {
      $keys=array_keys($member);
      sort($keys);
      foreach($keys as $key)
      {
        $val=$member[$key];
        unset($member[$key]);
        $member[$key]=$val;
      }
    }    
    
    echo "Original Array<br><br>";
    $member = array("Jack" => "55kg", "Bill" => "35kg", "Aaron" => "60kg", "Daniel" => "80kg" );
    foreach ($member as $user => $weight) { 
      echo "$user = $weight <br>";
    }
    
    echo "<br><br>";
    
    my_asort($member);
    echo "Sorted By user <br><br>";
    foreach ($member as $user => $weight) {
      echo "$user = $weight <br>";
    }
    
    echo "<br><br>";
    
    my_ksort($member);
    echo "Sorted By weight <br><br>";
    foreach ($member as $user => $weight) {
      echo "$user = $weight <br>";
    }