Jonathan Lyon
Jonathan Lyon

Reputation: 3952

Sort php array on one column and output to list

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

Upvotes: 0

Views: 1055

Answers (2)

mauris
mauris

Reputation: 43619

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');

Upvotes: 1

wnoveno
wnoveno

Reputation: 546

use array_multisort

Upvotes: 0

Related Questions