2013-06-26 90 views
0

我有一列我想排序的帖子 - 但在此之前,我想查找帖子的id,其中帖子的最大號碼爲likes。我使用foreach循環遍歷數組。儘管爲此做兩個foreach循環似乎是一種浪費 - 我不知道在嘗試事先找到最高值時是否有其他選擇?查找具有最高值的帖子的ID

Array 
(
    [0] => Array 
     (
      [id] => 162 
      [like_count] => 2 
      etc. 
     ) 
    [1] => Array 
     (
      [id] => 165 
      [like_count] => 23 
      etc. 
     ) 

) 

所以第二個職位有喜歡的最高金額,所以我需要的165號 - 然後當我遍歷我可以這樣做

foreach ($posts as $post){ 
    if($most_liked_id == $post["id"]){ 
     // this post is the most liked! 
    } 
} 

任何幫助將不勝感激 - 謝謝!

+0

你是什麼意思,兩個foreach循環? –

回答

1
$highest = 0; 
$highest_id = 0; 

foreach($array as $a) { 

    if($a['like_count'] > $highest) { 

     $highest = $a['like_count']; 
     $highest_id = $a['id']; 
    } 
} 

希望我理解正確的話,你:)

+0

選擇此作爲答案是最乾淨和最簡單的方法。 :)謝謝@paranoid。 – Tim

+0

哦,它不會重新排列我用來排序數據的原始SQL查詢中的數組。 – Tim

0

這看起來像從數據庫中檢索到的數據。如果是這樣,請使用SQL中的ORDER BY like_count DESC子句。

然後按照其他方法排序之前,喜歡最多的帖子的ID將在$posts[0]['id']

0

非常簡單的任務,你循環你的帖子。

function get_max_like_post($posts) { 
    $max_like = 0; 
    $max_like_post = array(); 
    foreach ($posts as $post) { 
     if ($post['like_count'] > $max_like) { 
      $max_like = $post['like_count']; 
      $max_like_post = $post; 
     } 
    } 

    return $max_like_post['id'] 
    } 
0

你可以使用usort

$posts = array(
    array('id' => 161, 'like_count' => 0), 
    array('id' => 162, 'like_count' => 6), 
    array('id' => 4, 'like_count' => 2), 
); 

function like_sort($a, $b) { 
    if ($a['like_count'] == $b['like_count']) { 
     return 0; 
    } 
    return ($a['like_count'] > $b['like_count']) ? -1 : 1; 
} 
usort($posts, 'like_sort'); 

// The first element in the array is now the one with the highest like_count. 
echo $posts[0]['id']; // 162 
+0

謝謝,這很好,但我不想重新排列數組,因爲它的順序是由其他東西定義的。 – Tim

+0

如果你想保留這個命令以後再用它的原始形式,我想你總是可以先複製它($ posts_ordered = $ posts)。但是(在我的例子中)如果$ posts是任何體面的大小,我們開始變得非常低效,而其他解決方案則更好。 – rebroken

0

嘗試這種情況:

usort($posts, function($item) { return -$item['like_count']; }); 
$id = empty($posts) ? null : $posts[0]['id']; 

$posts是輸入數組。

說明:

  • 首先你在降低的方式
  • 由像數的排序的職位,那麼你得到的最高職位ID,如果有任何職位,否則返回null。

這個解決方案的好處是,您還可以選擇第一個n的帖子。

0
$highest_post_likes = 0; 
$highest_post_id = 0; 
for($i = 0; $i < sizeof($posts); $i++) { 
    if ($posts[$i][like_count] > $highest_post_likes) { 
     $highest_post_likes = $posts[$i][like_count]; 
     $highest_post_id = $i; 
    } 
} 

// now you can use $posts[$highest_post_id] 
0

可以使用max函數獲取喜歡的最高值:

 foreach ($posts as $post){ 
     $max[]=$post['like_count']; 
    } 

echo max($max['id']); 
+0

謝謝,雖然這不會返回具有最高價值的帖子的id。 – Tim

+0

檢查我的更新答案。希望這會對你有用 –

0

是那些從DATAS像MySQL數據庫來的?如果是這樣,最簡單的解決方案是放置一個「ORDER BY」。

您還可以使'like_count'數組保持與第一個數組相同的密鑰並進行分配(http://www.php.net/manual/fr/function.asort.php)。你將擁有最高的計數密鑰。

0

您可以按照like_count的降序排列數組,然後爲第一個數組元素選取id