vote up 0 vote down star

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

Can someone please help with very clear instructions please.

Thanks in advance of your help.

Cheers

Jonathan

flag

33% accept rate

2 Answers

vote up 1 vote down

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');
link|flag
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 – Jonathan Lyon Oct 15 at 6:16
hi Jonathan, i noticed that your key is 'questions', not 'Question'. you might want to check that... – Mauris Oct 15 at 6:23
yep - I changed that function sort_callback($a, $b){ if ($a['questions'] == $b['questions']) { return 0; } return ($a['questions'] < $b['questions']) ? 1 : -1; } – Jonathan Lyon Oct 15 at 6:26
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. – Mauris Oct 15 at 6:32
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 – Jonathan Lyon Oct 15 at 6:41
show 3 more comments
vote up 0 vote down

use array_multisort

link|flag
please elaborate answer and give examples. – Mauris Oct 15 at 6:01
us2.php.net/manual/en/… – Mark Oct 15 at 6:16
@Mark i know. wnoveno should at least provide a better answer. – Mauris Oct 15 at 6:22

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.