Jump to content

Sort Two Dimensional Array


amedhussaini

Recommended Posts

???

 

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
Share on other sites

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
Share on other sites

<?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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.