35000, "Ben"=>25000, "Joe"=>48000); and I need to sort the array : 1) by value, ascending order" /> 35000, "Ben"=>25000, "Joe"=>48000); and I need to sort the array : 1) by value, ascending order" /> 35000, "Ben"=>25000, "Joe"=>48000); and I need to sort the array : 1) by value, ascending order"/>

Array Sorting in PHP. I need to write my own asort() and ksort() functions?

368 Views Asked by At

So I have this array

$employee_salary = array("Peter"=>35000, "Ben"=>25000, "Joe"=>48000);

and I need to sort the array : 1) by value, ascending order 2) by key, ascending order.

I am not allowed to use the asort and ksort functions, so I have no idea how else to do it. Any ideas please? Thank you!

2

There are 2 best solutions below

0
JP. Aulet On

¿Can't you use any php sorting methods, like usort() or asort()?

If yes: https://joshtronic.com/2013/09/23/sorting-associative-array-specific-key/

If no: yes, you must do it manually I guess, with array_walk() or something like this.

2
Kevin Gagnon On

I suppose that this is for an academic task.

Foreach loops lets you work with keys and values, as :

foreach($employee_salary as $employee => $salary){
   //do you comparison here, your manual sorting.
   //You could create 2 arrays here to store the value sort and the name sort.
}

Now, on StackOverflow you need to give more specific answer with a visual of the code but in this case, that would mean I do the exercise for you. Which I will not :)