1

I am trying to manually sort a PHP array without making use of ksort.

This is how my code looks at the moment:

function my_ksort(&$arg){
    foreach($arg as $key1 => $value1){
      foreach($arg as $key2 => $value2){
        if($key1 > $key2){
          $aux = $value2;
          $arg[$key2] = $value1;
          $arg[$key1] = $aux;
        }
      }
    }
}

It doesn't sort, I can't figure out how to make it sort.

Grant
  • 2,413
  • 2
  • 30
  • 41
Paul
  • 53
  • 6

4 Answers4

2

You could try this:

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

I'm sorting the keys separately and then deleting the elements one-by-one and appending them to the end, in ascending order.

I'm using another sorting function (sort()), but if you want to eliminate all available sorting functions from your emulation, sort() is much easier to emulate. In fact, @crypticous's algorithm does just that!

Community
  • 1
  • 1
geomagas
  • 3,230
  • 1
  • 17
  • 27
0

This function return array in ASC. Take in consideration that I'm using goto which is supported in (PHP 5 >= 5.3.0)

function ascending_array($array){
    if (!is_array($array)){
        $array = explode(",", $array);
    }

    $new = array();
    $flag = true;

    iter:
        $array = array_values($array); // recount array values with new offsets

        (isset($min["max"])) ? $min["value"] = $min["max"] : $min["value"] = $array[0];
        $min["offset"] = 0;

        for ($i=0;$i<count($array);$i++){
            if ($array[$i] < $min["value"]){ // redefine min values each time if statement executed
                $min["value"] = $array[$i];
                $min["offset"] = $i;
            }

            if ($flag){ // execute only first time
                if ($array[$i] > $min["value"]){ // define max value from array
                    $min["max"] = $array[$i];
                }
                $flag = false;
            }

            if ($i === (count($array)-1)){ // last array element
                array_push($new,$min["value"]);
                unset($array[$min["offset"]]);
            }
        }

    if (count($array)!=0){
        goto iter;
    }
    print_r($new);
}

$arr = array(50,25,98,45);

ascending_array($arr); // 25 45 50 98

PS. When I was studying php, I wrote this function and now remembered that I had it (that's why I really don't remember what I am doing in it, though fact is it's working properly and hopefully there are comments too), hope you'll enjoy :)

DEMO

nanobash
  • 5,419
  • 7
  • 38
  • 56
  • The usage of `goto` is a terrible practice. Even the [manual page](http://php.net/goto) says so. Are you sure there is no other alternatives? Like `do/while` ? – Touki Mar 10 '14 at 14:40
  • Am I missing something or this has _nothing to do with `ksort()`_? – geomagas Mar 10 '14 at 14:42
  • Alternatives are always in everything, just like you see I've written this code a long time ago, so I really don't going to start it from scratch. For studying and realizing purposes it is good I think – nanobash Mar 10 '14 at 14:43
  • @geomagas I've asked OP if he wanted `ASC` array function, and he answered YES, so I did post. Any problems ? – nanobash Mar 10 '14 at 14:44
  • Yes, `ksort()` sorts according to _keys_, yours doesn't. ASC or DESC is irrelevant. – geomagas Mar 10 '14 at 14:48
  • @geomagas Yes, it isn't sorting with keys, anyways hope OP find it interesting – nanobash Mar 10 '14 at 14:51
  • @crypticous Your code sorts the array by values and deletes the keys. I am trying to sort the keys and preserve the values. Nonetheless thank you. – Paul Mar 10 '14 at 14:52
  • @crypticous: I do find it too (especially `goto` - I hadn't seen _that_ for so many years). It's just that it's an answer to _another question_ and not the one at hand. – geomagas Mar 10 '14 at 14:52
  • @DragoslavPaul Yes, it's sorting with values (not with keys) – nanobash Mar 10 '14 at 14:54
  • @geomagas Maybe, I just wanted to help, that's all, anyways if it is any problem I'll delete it – nanobash Mar 10 '14 at 14:55
  • @DragoslavPaul Anyways I think you can copy that practice and do it with your own (try to change `goto` as well) – nanobash Mar 10 '14 at 14:59
  • @crypticous: No don't. In fact, I'm planning to link my answer to yours! :) – geomagas Mar 10 '14 at 15:01
0

I was checking some issue related to this post and i wanted to give my insight about it ! here's what i would have done to implement php's sort :

$array_res = array();
$array = array(50,25,98,45);
$i=0;

 $temp = $array[0];
 $key = array_search($temp, $array);
while ($i<count($array)-1){

     $temp = $array[0];
    for($n=0;$n<count($array) ;$n++)
    {

        if($array[$n]< $temp && $array[$n] != -1 )
        {

             $temp = $array[$n];

        }
        else{continue;}
    }
//get the index for later deletion
$key = array_search($temp, $array);



array_push($array_res, $temp);
/// flag on those which were ordered
$array[$key] =-1;

$i++;
}

// lastly append the highest number 

for($n=0;$n<count($array) ;$n++)
        {
            if ($array[$n] != -1)

            array_push($array_res, $array[$n]);

        }
// display the results
print_r($array_res);

This code will display : Array ( [0] => 25 [1] => 45 [2] => 50 [3] => 98 )

0

Short and sweet

function custom_ksort($arg)
{
    $keys = array_keys($arg);

    sort($keys);

    foreach($keys as $newV)
    {
        $newArr[$newV] = $arg[$newV];
    }

    return $newArr;
}
TarangP
  • 2,711
  • 5
  • 20
  • 41