drexlz0623 2011-08-10 10:54
浏览 55
已采纳

自定义数组排序

At first - yes, I've tried to find my problem here, but can't make it.

I have a problem with array sorting. I want to use custom array sorting to sort some data taken from DB.

For example, I have array

values: [ 0, 0, 0, 0, 14830, 78426, 0, 0, 0, 0, 0, 0, 6024, 1144, 4438, 19282 ]

And I need to get last 4 (sometimes 3 or 2, so it would be custom) results on the first place in the same order as they are now. And the result should be like:

values: [ 6024, 1144, 4438, 19282, 14830, 78426, 0, 0, 0, 0, 0, 0,]

How can I do that?

I make this array with

while($row=mysql_fetch_array($re))
{
$dates = $row['mon'];

 while ($current_month != $dates) {
  $current_month = $current_month + 1;
  if($current_month == 13)
  $current_month = 1;
  $data[] = 0;
 }
 $data[] = intval($row['type']);
 $current_month = $dates+1;
}

I take months number as $current_month and using it puts my data in right places. When month have no results it adds 0 in that place. The results should be just 6 and when there's no passing through the years it makes array right, but sometimes it goes wrong like this, so I want to make proper array using custom sorting like I mantioned at first.

So I want to sort this array and with array_slice cut it to 6.

Thanks for help.

  • 写回答

3条回答 默认 最新

  • dongyiyu3953 2011-08-10 11:02
    关注
    $desired_length = 4;
    $arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
    $length = count($arr);
    $array = array_slice($arr, $length-$desired_length, $desired_length) + array_slice($arr,0,$length-$desired_length);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果