0

I have an array that looks like this:

{ [0]=> array(4) { "20" ["date"]=> string(10) "2013-01-25" ["content"]=> string(3) "ref" }

and [1], [2]... looks the same.

I wonder how to order my array so [0] is the one the latest date. Changing to timestamp is not an opinion. Any ideas?

3 Answers 3

1

use order by in your query.

ORDER BY date
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking if there's a way to do it with the array instead, there's multiple queries
1

You can use usort() and write your own comparison function (a function that compares between "objects" - the inner arrays).

Since the dates are written in a way that enables simple string comparison you can do as follows:

<?php
function compare($arr1, $arr2) {
   $date1 = $arr1[0];
   $date2 = $arr2[0];
   if($date1 > $date2){
       $ans = 1;
   }
   else if($date2 > $date1){
       $ans = -1;
   }
   else{
       $ans = 0;
   }
   return $ans;
}

$arr = array(array("date"=>"2013-01-25", "content"=>"ref"), 
                array("date"=>"2013-02-25", "content"=>"ref2"), 
                array("date"=>"2013-03-25", "content"=>"ref3")
        );

usort($arr, "compare");
print_r($arr);

?>

OUTPUT:

Array
(
    [0] => Array
        (
            [date] => 2013-03-25
            [content] => ref3
        )

    [1] => Array
        (
            [date] => 2013-02-25
            [content] => ref2
        )

    [2] => Array
        (
            [date] => 2013-01-25
            [content] => ref
        )

)

Comments

0

Try this : This sorts multi dimensional array

$sort = array();
foreach($your_array as $k=>$v) {
    $sort['date'][$k] = $v['date'];
}

array_multisort($sort['date'], SORT_DESC, $your_array);


echo "<pre>";
print_r($your_array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.