biggieuk Posted February 15, 2011 Share Posted February 15, 2011 Hi all, I have a multi-dimensional array looking somewhat like the following: Array ( [0] => Array ( [id] => 853 [title] => item 853 [price] => 17.99 [createdtime] => yyyy-mm-dd 00:00:00 ) [1] => Array ( [id] => 854 [title] => item 854 [price] => 11.99 [createdtime] => yyyy-mm-dd 00:00:00 ) ... I need to re-order this array so that any items with the 'createdtime' within a month from todays date are at the top, followed by all of the other items in the original order. I would usually amend the sql but I need to do this with the array. What would be the best way to do this? I found array_multisort but im not too sure how to adapt this to my needs. Thank you for any help with this! Quote Link to comment Share on other sites More sharing options...
Simmo Posted February 15, 2011 Share Posted February 15, 2011 Hi, I have done something similar and this help me from the php.net <?php $data[] = array('volume' => 67, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 1); $data[] = array('volume' => 85, 'edition' => 6); $data[] = array('volume' => 98, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 6); $data[] = array('volume' => 67, 'edition' => 7); ?> <?php // Obtain a list of columns foreach ($data as $key => $row) { $volume[$key] = $row['volume']; $edition[$key] = $row['edition']; } // Sort the data with volume descending, edition ascending // Add $data as the last parameter, to sort by the common key array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data); ?> But you must remember that wen you loop through the neww sorted array to use the same format as it is in the foreach loop, using the row names. Quote Link to comment Share on other sites More sharing options...
silkfire Posted February 15, 2011 Share Posted February 15, 2011 Try this, it's an algorith that makes an array out of the months and sorts them, then creates a new array based on the sorted months ($a is your array!): $months = $finished = array(); foreach ($a as $n => $bag) $months[$bag['createdtime']] = $n; ksort($months); foreach ($months as $masterindex) $finished[] = $a[$masterindex]; return $finished; Quote Link to comment Share on other sites More sharing options...
biggieuk Posted February 15, 2011 Author Share Posted February 15, 2011 Both work brilliant, thanks very much for your help Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.