Yash
Yash

Reputation: 171

how to sort associative array according to key without using any php built in function

     $array = array(
        '2' => 'a',
        '5' => 'b',
        '1' => 'c',
        '5' => 'd',
        '3' => 'e'
    )

foreach($array as $key => $value){

        $array1 = $array;
        foreach($array1 as $key1 => $value1){
            if($key > $key1){
                $result[$key1] = $value1;
            }
        }
}

    print_r($result);

this is my output:

Array
(
    [1] => c
    [2] => a
    [3] => e
)

i am making comparison of key with same key by storing this array in another array, if num > num in this case the maximum number 5(5>5) this condtions fails so 5 is not in the new array. so please can anyone tell me how this will sort or is there any better way. thanks in advance.

Upvotes: 1

Views: 3603

Answers (1)

Fabricator
Fabricator

Reputation: 12772

Your algorithm does not work because the outer loop iterate over each key, and inner loop will try to insert any keys less than the current key into the array. Although these keys are smaller than the current key, but it does not guarantee they are in ascending order. For example, the following array will not work:

array(
  3 => 'a',
  2 => 'b',
  1 => 'c'
);

Of course it has the issue of missing some element from the original array as you may have already noticed.

Instead you can use any sorting algorithm (like mergesort, quicksort, etc) to sort the keys first, then build the new associative array. Below implements insertion_sort (because it is easy to do).

function insertion_sort($arr)
{
    for ($i = 0; $i < count($arr); $i++) {
        $j = $i;
        while ($j > 0 && $arr[$j] < $arr[$j-1]) {
            $tmp = $arr[$j-1];
            $arr[$j-1] = $arr[$j];
            $arr[$j] = $tmp;
            $j--;
        }
    }

    return $arr;
}

$array = array(
    '2' => 'a',
    '5' => 'b',
    '1' => 'c',
    '5' => 'd',
    '3' => 'e'
);
$keys = array_keys($array);

$sorted = array();
foreach (insertion_sort($keys) as $key) {
    $sorted[$key] = $array[$key];
}

print_r($sorted);

prints

Array
(
    [1] => c
    [2] => a
    [3] => e
    [5] => d
)

Upvotes: 2

Related Questions