Jump to content

Sort array by most recent for this month.


biggieuk

Recommended Posts

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!

 

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.

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;

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.