I know there have been many posts regarding array sorting, but I have looked high and low and cannot find a solution to my problem.
I have found a very good article here: http://firsttube.com/read/sorting-a-multi-dimensional-array-with-php/
The above link is great, however, I wish to take it further and sort the array subkey based off the order of another array.
So, let's say we have five songs in the Playlist Array:
Array
(
[0] => 3oh!3 - Don't Trust me
[1] => Taylor Swift - You Belong with me
[2] => Sean Kingston - Fire Burning
[3] => Green Day - Know Your Enemy
[4] => Kelly Clarkson - Gone
)
And let's say we have the following information that we would like sorted to match the order of our Playlist Array:
Array
(
[0] => Array
(
[trackName] => Taylor Swift - You Belong With Me
[trackLength] => 0
[trackViews] => 0
[trackRating] => 0
)
[1] => Array
(
[trackName] => Sean Kingston - Fire Burning
[trackLength] => 0
[trackViews] => 0
[trackRating] => 0
)
[2] => Array
(
[trackName] => 3OH!3- Dont Trust Me
[trackLength] => 205
[trackViews] => 4570399
[trackRating] => 4.866372
)
[3] => Array
(
[trackName] => Green Day Know Your Enemy
[trackLength] => 191
[trackViews] => 4715494
[trackRating] => 4.9103785
)
[4] => Array
(
[trackName] => Kelly Clarkson: Gone
[trackLength] => 225
[trackViews] => 679019
[trackRating] => 4.8995433
)
)
So, again... My question is: How can I get the array of songs to be sorted by the trackName to match the same order of the Playlist Array?
Any help or guidance would be appreciated!
Thanks.
[SOLUTION] EDDIE had the master winning solution! Props to him! 1up his answer! :)
However, I modified eddie's solution slightly. I just added a similarity check of 75% between the user entered song titles and the song titles looked up on the external sources because I cannot control the slight variations of each title.
$sorted_list = array();
foreach($songs as $song_key=>$song){
foreach($song_info as $info){
similar_text($info['trackName'], $song, $p);
if($p > 75){
$sorted_list[$song_key] = $info;
}
}
}
it is not effectivily but should works:
Hakre's idea:
You get the weight in sort from the position of each trackname in the playlist.
So you need to find each track inside the playlist (position) to get the weight of a track in the track-list.
You can then use that order to sort the track-list (Demo):
Note: This does only work when the trackname in the playlist is the same as the trackname inside the track-list. With the example data you gave in your question, that was not the case.
Additionally I simplified your
$tracks
data a bit, each element can have any amount of additional elements naturally.Assuming your playlist is in the array $songs and your other array is in $songs_info.