sort associate array in PHP -
function mysort($arr) { ($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( 'a' => '1', 'f' => '3', 'g' => '5', 's' => '2', 'r' => '8' ); $values = array_values($array); $sorted = array(); foreach (mysort($values) $key=> $value) { $sorted[$value] = $array[$value]; } print_r($sorted); i lost here. i'd sort array $array according values output
a = 1
s = 2
f = 3
g = 5
r = 8
however trying without using sort methods such asort, usort or ksort. own function.
this should work you:
here simple loop through elements of $array , save them sorted in $sorted. in first if statement check if either $sorted array empty or current element of $array bigger last element of sorted array. if true append element @ end $sorted array.
e.g. (pseudo code):
empty($sorted) || end($sorted) < current($array) otherwise i'll enter else part loop through $sorted array find spot current element of $sorted less current element of $array , next element of $sorted bigger current element of $array (so find spot current element of $array has go in between).
e.g (pseudo code):
current($sorted) < current($array) && next(current($sorted)) > current($array) and if case first cut off part current element of $sorted array , save in tmp variable. append current element $array , append part cut off again @ end of $sorted array.
<?php $array = [ 'a' => '1', 'r' => '8', 'g' => '5', 'f' => '3', 's' => '2', ]; $sorted = []; $keys = array_keys($array); for($count = 0; $count < count($array); $count++) { $tmpkeys = array_keys($sorted); if(empty($sorted) || $sorted[$tmpkeys[count($sorted)-1]] < $array[$keys[$count]]) { $sorted[$keys[$count]] = $array[$keys[$count]]; } else { for($innercount = 0; $innercount < count($sorted)-1; $innercount++) { if($sorted[$tmpkeys[$innercount]] < $array[$keys[$count]] && $array[$keys[$count]] < $sorted[$tmpkeys[$innercount+1]]) { $tmp = array_splice($sorted, $innercount+1); $sorted[$keys[$count]] = $array[$keys[$count]]; $sorted = array_merge($sorted, $tmp); } } } } print_r($array); print_r($sorted); ?> output:
array ( [a] => 1 [r] => 8 [g] => 5 [f] => 3 [s] => 2 ) array ( [a] => 1 [s] => 2 [f] => 3 [g] => 5 [r] => 8 )
Comments
Post a Comment