chasethesunnn
chasethesunnn

Reputation: 2234

ordering a php array by sorting one of its values

I have an array of items that i want to sort by how many likes each item has with the highest first.

I tried to order the likes for each item, but in the way that i went about it, there was no more association to the original item.

Here is what i did:

$max = $feed->get_item_quantity(); //max number of items in the array
$orderedLike;
for($i = 0; $i < $max; $i++ )
{
    $item[$i] = $feed->get_item($i); //gets single items
    $orderedLike[$i] = $item[$i]->get_like_count(); //gets number of likes for each item
}
arsort($orderedLike); //sorts the number of likes
echo '<pre>';
    foreach ( $orderedLike as $like )
    {
        echo $like . ' '; //displays the likes
    }
echo '</pre>';

This works but then i realized that i cant sort the original array of items anymore because there are two arrays. One with numbers of likes and one with items and values(including the number of likes).

The array im ultimately trying to get into order via the like value is $item

Im not quite sure how to do this.

Upvotes: 0

Views: 84

Answers (2)

Paul
Paul

Reputation: 141877

You can use usort for this:

usort($item, 'cmp_by_likes');

function cmp_by_likes($a, $b){
    return $b->get_like_count()-$a->get_like_count();
}

Upvotes: 4

cwallenpoole
cwallenpoole

Reputation: 82048

You're actually not far off. You can use foreach( $arr as $key => $val ) to do that:

foreach ( $orderedLike as $key => $val )
{
    echo $item[$key]. ' '; //displays the likes
}

But maybe you're better off with usort:

// I never say this initialized.
$item = array();
// create only one array
for($i = 0; $i < $max; $i++ )
{
    // let PHP handle indexing.
    $item[] = $feed->get_item($i); //gets single items
}    
usort( $item, 'sort_by_like_count' );
// item is now sorted by get_like_count

function sort_by_like_count( $a, $b )
{
    $a = $a->get_like_count();
    $b = $b->get_like_count();
    // you can do return $a - $b here as a shortcut. I prefer being explicit as
    // 1, 0, -1 is expected more universally.
    if( $a == $b ) return 0;
    return ( $a > $b )? 1: -1;
}

Upvotes: 1

Related Questions