0

I have an array in following format:

array( 
    [0]=> array(
        [0]=> array ( 
            ["ID"]=> 118
            ["post_date"]=> "2014-04-28 07:27:37" 
            ["post_title"]=> "Title 1"
        )
        [1]=> array ( 
            ["ID"]=> 119
            ["post_date"]=> "2014-04-29 07:27:37" 
            ["post_title"]=> "title 2"
        )
    )
    [1]=> array(
        [0]=> array ( 
            ["ID"]=> 135
            ["post_date"]=> "2014-04-28 06:37:37" 
            ["post_title"]=> "Title 3"
        )
        [1]=> array ( 
            ["ID"]=> 148
            ["post_date"]=> "2014-04-25 07:27:37" 
            ["post_title"]=> "Title 4"
        )
    )
    [2]=> array(
        [0]=> array ( 
            ["ID"]=> 135
            ["post_date"]=> "2014-04-24 06:37:37" 
            ["post_title"]=> "Title 5"
        )
        [1]=> array ( 
            ["ID"]=> 148
            ["post_date"]=> "2014-04-25 09:21:37" 
            ["post_title"]=> "Title 6"
        )
    )
)

Now I need to sort this using post_date and show them in DESC order. This is in PHP.

I am not sure how to sort this. Can anybody please help me with this sorting?

This is how I want to show the output:

title 2
Title 1
Title 3
Title 6
Title 4
Title 5
8
  • 1
    possible duplicate of Sort Multi-dimensional Array by Value Commented May 4, 2014 at 15:45
  • "sort this using post_date" - which post_date? Each array element ultimately contains two, which appear to differ unpredictably. Commented May 4, 2014 at 15:47
  • show how you want the output look like? Commented May 4, 2014 at 15:52
  • @Nazin I have got an extra level deeper, than that one. But I will try with that answer. Commented May 4, 2014 at 16:06
  • 1
    So you are saying you want to flatten the top-level array and then sort using the post_dates of the flattened array? This is really two operations that need to be composed together. The flattening step can be accomplished using a loop. The sorting can be achieved using Petah's answer to the question linked by Nazin. Commented May 4, 2014 at 16:46

1 Answer 1

2

Okay, I have solved it by flattening the array and then applying usort. This is how I have done it:

$query_results; //this is my main array
$flatten_array =array();
foreach ($query_results as $data) {
    foreach($data as $flatten_data) {
        $flatten_array[] = $flatten_data;
    }
}

function cpt_array_sort($a, $b) {
    return strtotime($b->post_date) - strtotime($a->post_date);
}

usort($flatten_array, 'cpt_array_sort');
Sign up to request clarification or add additional context in comments.

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.