If I have an associative array like
3 => 50
4 => 12
5 => 45
6 => 89
7 => 5
8 => 1
Now I want to sort only the values of odd keys in ascending order. The output should be:
7 => 5
4 => 12
5 => 45
6 => 89
3 => 50
8 => 1
To maintain original keys, you have to first separate even and odd elements:
$odd = $even = array();
array_walk( $array, function( $val, $key ) use ( &$odd, &$even ) { ( $key % 2 ) ? $odd[$key] = $val : $even[$key] = $val; });
Then, sort $odd array:
asort( $odd );
At the end, you reconstruct the array:
$array = array();
while( current( $odd ) || current( $even ) )
{
if( current( $odd ) ) $array[key($odd)] = current( $odd );
if( current( $even ) ) $array[key($even)] = current( $even );
next( $odd );
next( $even );
}
print_r( $array );
eval.in demo
Note that your question is a bit ambiguous: it's not totally clear if you base odd/even on key value or key position: this solution consider key values and — trough while and if checks — guarantee that all values are preserved, even if you have more even than odd keys (or vice-versa).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With