php sort assoc array keys values

 avatar
unknown
php
2 years ago
1.8 kB
3
Indexable
/*

array(7) {
  ["a"]=>
  int(1223)
  ["b"]=>
  int(132)
  ["c"]=>
  int(12)
  ["d"]=>
  int(99)
  ["e"]=>
  int(25)
  ["f"]=>
  int(214123)
  ["g"]=>
  int(17)
} 

TO --- >

array(7) {
  ["c"]=>
  int(12)
  ["g"]=>
  int(17)
  ["e"]=>
  int(25)
  ["d"]=>
  int(99)
  ["b"]=>
  int(132)
  ["a"]=>
  int(1223)
  ["f"]=>
  int(214123)
}

*/

/**
 * @param int $count count items to return in result
 * @param bool $reverse reverse result items ?
 * 
 * @return array|null sorted array
 */
function assoc_sort_keys_with_value( $arr, $count = false, $reverse = false) {
    
    if( empty( $arr ) ) {
        return null;
    }

    $len = count($arr);
    
    $custom_arr = [];
    
    foreach( $arr as $k => $v ) {
        $custom_arr[] = [
            'k' => $k,
            'v' => $v,
        ];
    }


    for( $i = 0; $i < $len; $i++ ) {
        foreach( $custom_arr as $k => $obj ) {
            if( $k > 0 ) {
                if( !$reverse ? $custom_arr[$k-1]['v'] > $obj['v'] : $custom_arr[$k-1]['v'] < $obj['v'] ) {
                    $custom_arr[$k]['v'] = $custom_arr[$k-1]['v'];
                    $custom_arr[$k]['k'] = $custom_arr[$k-1]['k'];
                    $custom_arr[$k-1]['v'] = $obj['v'];
                    $custom_arr[$k-1]['k'] = $obj['k'];
                }
            }
        }
    }

    $arr = [];
    foreach( $custom_arr as $k => $obj ) {
        $arr[$obj['k']] = $obj['v'];
    }

    if( $count !== false && $count > 0 ) {
        $i = 0;
        foreach( $arr as $k => $v ) {
            if( $i >= $count ) {
                unset( $arr[$k] );
            }
            $i++;
        }
    }
 
    unset($custom_arr);
    unset($count);
    unset($len);

    return $arr;
}