2011-07-27 35 views
0

我有一个项目数组,我想按每个项目具有最高优先级的数量来排序。通过对其中一个值进行排序来订购php数组

我试着为每件商品订购喜欢的商品,但是就我所了解的方式而言,与原始商品没有更多关联。

这里是我做的:

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

这工作,但后来我意识到,我不能因为有两个数组项目的原始排列了排序。一个有喜欢的数字,一个有项目和值(包括喜欢的数字)。

阵列IM最终要通过类似的值来进入顺序是$item

林不太清楚如何做到这一点。

+1

你也可以用在array_multisort()函数,如果你想..... – Pushpendra

回答

1

你其实并不遥远。您可以使用foreach($arr as $key => $val)做到这一点:

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

但是,也许你最好用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; 
} 
+0

你会如何颠倒数组的顺序从最高到最低?其最低的第一个到最高的这个设置 –

+1

@Nils R这就像改变返回到'返回($ a <$ b)一样简单? 1:-1;' – cwallenpoole

4

您可以使用usort此:

usort($item, 'cmp_by_likes'); 

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

会怎样你将数组的顺序从最高到最低颠倒过来? –

+1

@Nils我编辑了我的帖子以反转订单。只需在比较函数中交换'$ a'和'$ b',以便它们相反排列。 – Paulpro

相关问题