0

I have created an array that is populated from a wordpress loop:-

<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
     
        $alisting []["questions"] = $questions; 
        $alisting []["id"] = $post->ID; 
        $alisting []["title"] = $post->post_title; 
      
<?php endwhile; ?>

This outputs

Array ( [0] => Array ( [questions] => 22 ) [1] => Array ( [id] => 1016 ) [2] => Array ( [title] => Cash Commons ) [3] => Array ( [questions] => 15 ) [4] => Array ( [id] => 811 ) [5] => Array ( [title] => The Poker Echo ) [6] => Array ( [questions] => 34 ) [7] => Array ( [id] => 437 ) [8] => Array ( [title] => VideoWTF.com ) [9] => Array ( [questions] => 34 ) [10] => Array ( [id] => 295 )

I need to sort this array by Questions in descending order and echo it out to a list so that I will have:-

ID       | Title           |  Question

1023       Cash Commons       43
987        Videowtf           34

etc

2 Answers 2

1

You will need to use the function uasort() - http://www.php.net/manual/en/function.uasort.php - and create a call back function to sort.

function sort_callback($a, $b){
    if ($a['Question'] == $b['Question']) {
        return 0;
    }
    return ($a['Question'] < $b['Question']) ? 1 : -1;
}

uasort($alisting,'sort_callback');
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks Mauris - doesn't seem to have worked. I wish it wasn't this hard. Here's the output using this:- $length = count($alisting); for ($i = 0; $i < $length; $i++) { echo $alisting[$i]['questions'].'<br>'; } 23 15 34 34 31 8
hi Jonathan, i noticed that your key is 'questions', not 'Question'. you might want to check that...
yep - I changed that function sort_callback($a, $b){ if ($a['questions'] == $b['questions']) { return 0; } return ($a['questions'] < $b['questions']) ? 1 : -1; }
Hi there i noticed it's because you are using $i for the index. the index are not changed, the order are. you might want to use var_dump to see it, or use a foreach.
This is driving me mad - why is it so hard - can someone please help with a code example that can work - I really need this
|
0

use array_multisort

3 Comments

please elaborate answer and give examples.
@Mark i know. wnoveno should at least provide a better answer.
This hint should have been a comment instead of an answer.

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.