Jump to content

sorting by an element within an array within an array


ffej2ffej
 Share

Recommended Posts

I have an array full of smaller arrays. The smaller arrays contain elements, one of which is a date. (Not a timestamp, a date such as 1, 2, 3, etc.) I want to sort the small arrays within the large array in order of this date. I don't see anything in the docs for PHP on how to do this.Let me state this another way. I have an array called $eventsThisMonth. I would like to sort $eventsThisMonth by $eventsThisMonth[every][dateOfThisOccurrance]. Thank you in advance for your great help and advice. Jeff P.S. I tried sorting "manually" using an outside loop that goes 1-31 (for the possible values of the date) and an inner loop that goes 0-count($eventsThisMonth) and compares the dateOfThisOccurrance of each smaller array to the index of the outside loop. If equal, it does an array_push to another array. This still didn't work; the other array was in the same order as the original.

Link to comment
Share on other sites

Ok, here is my attempt to "manually" sort. The code follows. for($x=1;$x<32;$x++){for($y=0;$y<count($thisMonthArray);$y++){if($thisMonthArray[$y][dateOfThisOccurance]==$x){array_push($thisMonthArraySorted,$thisMonthArray[$y]);echo "<script>alert('x='.$x.'y='.$y)</script>";}//closes if()}//closes inner loop (all elements in $thisMonthArray)}//closes outer loop (1 - 31) echo "<table border=3><tr><td>Event Name</td><td>Organization</td><td>Event Date</td><td>Event Description</td></tr>";for($i=0;$i < count($thisMonthArraySorted);$i++){echo "<tr><td>".$thisMonthArraySorted[$i][eventName]."</td><td>".$thisMonthArraySorted[$i][nameAddressPhone]."</td><td>".$thisMonthArraySorted[$i][dateOfThisOccurance]."</td><td>".$thisMonthArraySorted[$i][description]."</td></tr>";}//closes for()echo "</table>";

Link to comment
Share on other sites

I fixed it. I realized the problem was not with the sorting mechanism, but the fact that I was sorting a date (01, 02, etc.) to a string of the entire date. I extracted the substring then compared it and it works fine. I did not use any of the sorting functions built in to PHP, but rather used my own algorithm. The way I'm imagining the site in full use, it won't really matter because there won't ever be any more than a few dozen (at worst) records to sort.Thank you all for your suggestions and help.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...