-2

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!

K. Sm.
  • 27
  • 3
  • Read up on how sorting works :) – JimL Mar 13 '16 at 21:10
  • @K.Sm. show how should look the expected result – RomanPerekhrest Mar 13 '16 at 21:28
  • @RyanVincent it's a very common programming class assignment :) – JimL Mar 13 '16 at 21:44
  • Yes, it is for an assignment. A few tips are fine, I didn't expect a full code from you. It's just that our teacher didn't really explain PHP in depth so it's really difficult for us to do it without using the asort and ksort functions. Thanks anyway. – K. Sm. Mar 13 '16 at 21:53
  • There are a lot of different ways to sort an array manually https://en.wikipedia.org/wiki/Sorting#A_few_different_algorithms_that_are_popular_in_computer_science I suggest you pick one and look at how you can mimic the process. Come back if you run into issues with your attempt and you'll get the help you need. I don't recommend blindly copy-pasting from the link Paul posted, you'll get busted. – rjdown Mar 13 '16 at 21:55

2 Answers2

0

¿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.

JP. Aulet
  • 4,117
  • 3
  • 21
  • 34
0

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 :)

Kevin Gagnon
  • 142
  • 11
  • Haha thank you, I didn't expect anyone here to do my homework for me anyway. A few tips are fine! – K. Sm. Mar 13 '16 at 21:48
  • Now your best guess would go and look how sorting algorithms work and do your own, based on them. Sorting algorithm are super fun, try to add your touch to make as optimized as possible. Also, for the challenge, in the foreach loop, try to sort both entries you have to sort at the same time. Get the extra points ! – Kevin Gagnon Mar 13 '16 at 21:55