- Word of the day: Ouch.
- I’m done with the cancer, but the cancer isn’t done with me
- Goodbye, my dopey dog.
- So long, Alex King
Polluting the internet since 2004
August 21, 2009 | PHP Scripting
This one is pretty fun. Well, at least I think it is.
I was working with jQuery UI Sortables the other day and getting the reordered elements from jQuery back in to PHP for reordering via Ajax I ended up with an array whose elements matched the array keys of the array that I needed to order. Pretty standard fare. But I knew that there had to be a keen way to tackle the reordering process without going through some convoluted code. I was right. The way was the merge the two arrays.
The way array_merge works is if your array keys are non-numeric and that if the second given array has the same keys as the first given array the data from the second given array replaces the data in the first given array without reordering the first given array.
This was perfect since the two arrays will match perfectly in length and keys since they were built off the same data. This meany that all I had to do was take the new order data from jQuery Sortable, apply array_flip and merge the old ordered array in to the new order. Like so:
This code outputs:
So, the array is reordered without any hubbub. Nothing groundbreaking, just another way to reduce a few lines of code and not have to try and re-invent the wheel.
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
[…] Use array_merge to reorder arrays – this is handy. […]
August 24, 2009 | 7:25 am
Comments are closed