dongzhiyong8577 2013-06-26 08:00
浏览 19
已采纳

找到具有最高价值的帖子的ID

I have an array of posts that I want to sort - but before I do, I want to find the id of the post with the highest number of likes.

I loop through the array using a foreach. Although it seems like a waste to do two foreach loops for this - I don't know if there's an alternative when trying to find the highest value beforehand?

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

)

So the second post has the highest amount of likes, so I need the ID of 165 - then when I loop through I can do something like

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

Any help would be much appreciated - thanks!

  • 写回答

9条回答 默认 最新

  • dongra1984 2013-06-26 08:05
    关注
    $highest = 0;
    $highest_id = 0;
    
    foreach($array as $a) {
    
        if($a['like_count'] > $highest) {
    
            $highest = $a['like_count'];
            $highest_id = $a['id'];
        }
    }
    

    Hope I understood you correctly :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数