Posts

Showing posts with the label Associative Array

Bash Associative Array Sorting By Value

Answer : You can easily sort your output, in descending numerical order of the 3rd field: for k in "${!authors[@]}" do echo $k ' - ' ${authors["$k"]} done | sort -rn -k3 See sort(1) for more about the sort command. This just sorts output lines; I don't know of any way to sort an array directly in bash. I also can't see how the above can give you names ("Pushkin" et al.) as array keys. In bash, array keys are always integers. Alternatively you can sort the indexes and use the sorted list of indexes to loop through the array: authors_indexes=( ${!authors[@]} ) IFS=$'\n' authors_sorted=( $(echo -e "${authors_indexes[@]/%/\n}" | sed -r -e 's/^ *//' -e '/^$/d' | sort) ) for k in "${authors_sorted[@]}"; do echo $k ' - ' ${authors["$k"]} done Extending the answer from @AndrewSchulman, using -rn as a global sort option reverses all columns. In this example, author...

Change $key Of Associative Array In A Foreach Loop In Php

Answer : unset it first in case it is already in the proper format, otherwise you will remove what you just defined: foreach($array as $key => $value) { unset($array[$key]); $array[ucfirst($key)] = $value; } You can't modify the keys in a foreach , so you would need to unset the old one and create a new one. Here is another way: $array = array_combine(array_map('ucfirst', array_keys($array)), $array); Get the keys using array_keys Apply ucfirst to the keys using array_map Combine the new keys with the values using array_combine The answers here are dangerous, in the event that the key isn't changed, the element is actually deleted from the array. Also, you could unknowingly overwrite an element that was already there. You'll want to do some checks first: foreach($array as $key => $value) { $newKey = ucfirst($key); // does this key already exist in the array? if(isset($array[$newKey])){ // yes, sk...