amedhussaini Posted December 7, 2008 Share Posted December 7, 2008 ??? Ugh. I've been googling this and reading the php manual for hours now, but I can't quite figure out how to sort a 2d array. I always reserve this place as a last resort, I hate to fill up these boards with simpleton questions. Here goes: I have a 2 array called $final, some example output: $final[0][0] contains the string "pregnancy" $final[0][1] contains the integer "25" $final[1][0] contains the string "baby" $final[1][1] contains the integer "14" You might have guessed, I've written a scraper that ranks the amount of key words on a page. I have the $final 2d array with each keyword and the amount of times they appear, but they're out of order. How might I sort this array by the integer DESC? Thanks so much in advance. Link to comment https://forums.phpfreaks.com/topic/135872-sort-two-dimensional-array/ Share on other sites More sharing options...
KrisNz Posted December 7, 2008 Share Posted December 7, 2008 Is there any reason your array can't be structured like $['keyword'] = $timesAppearedOnPage; ?? Link to comment https://forums.phpfreaks.com/topic/135872-sort-two-dimensional-array/#findComment-708282 Share on other sites More sharing options...
marcus Posted December 7, 2008 Share Posted December 7, 2008 Why don't you sort the numbers with the numbers and the words with the words, and just assign a key to them. Link to comment https://forums.phpfreaks.com/topic/135872-sort-two-dimensional-array/#findComment-708286 Share on other sites More sharing options...
amedhussaini Posted December 7, 2008 Author Share Posted December 7, 2008 Hello, Thanks for the suggestions. I just read up on array keys. I could use an associated array storing each key word and corresponding numbers--are there other ways? How would I assigned a key between two arrays to preserve order when sorting (a quick code snippet if possible).. I'm going to try to implement the associate array and do a simple sort on that but I'd love to see multiple ways of doing for the learning factor. Thanks!! Link to comment https://forums.phpfreaks.com/topic/135872-sort-two-dimensional-array/#findComment-708566 Share on other sites More sharing options...
premiso Posted December 7, 2008 Share Posted December 7, 2008 <?php $final['pregnancy'] = 25; $final['baby'] = 14; sort($final); print_r($final); ?> Would be easier than the 2-dimm. sort As far as multiple ways, why use another way when there is a best way to do this. As far as I know this is the best way, any other way would be excessive, inefficient and not worth your time to learn because for this scenario, this is the best way to do it. Link to comment https://forums.phpfreaks.com/topic/135872-sort-two-dimensional-array/#findComment-708567 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.