douyingp82418 2013-07-16 21:07
浏览 11
已采纳

我有一个多维数组,需要通过“列”对其进行排序,但保持其他列的组织[重复]

This question already has an answer here:

my array have this structure:

$news = array('id' => '', 'views' => '');

i need to order this by the most viewed, but it have to match the id. I've done some research but got many doubts.

</div>
  • 写回答

1条回答 默认 最新

  • doutenglou6588 2013-07-16 21:10
    关注

    I'm having some trouble deciphering exactly what you mean with the question but here a couple of thinks that may work for you.

    if your array is composed like

    array(
          array("id"=>1, "views"=>50),
          array("id"=>3, "views"=>16)
    );
    

    Then you can use usort with a closure(php 5.3)

    usort($news, function ($a, $b){ return $a["views"] - $b["views"]});
    

    if you want it in descending order you can just swap the $a and $b in the closure

    usort($news, function ($a, $b){ return $b["views"] - $a["views"]});
    

    If you have an array that is composed like

    array(
         "id"=>array(1,2),
         "views"=>array(50, 16)
    );
    

    Then you can use array_multisort

    array_multisort($news["views"], $news["id"]);
    

    or if you want it in descending order

    array_multisort($news["views"], SORT_DESC, SORT_NUMERIC, $news["id"]);
    

    UPDATE

    The final solution.. news was an object with a views and id array properties. The final solution was:

    array_multisort($news->views, $news->id);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?