在数组中排序时间

时间:2017-12-13 20:15:24

标签: javascript php arrays sorting time

我从API收到了一些数据,我需要按时排序(iStart)有谁知道怎么做?这个数组有12个项目,其中包含如下信息:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        // handling layout
        // which needs to be centered vertically and horizontally
        // also:
        // maximum number of items = 6
        // maximum number of rows = 2
        // maximum number of items in row = 3
        let numberOfItems: CGFloat
        let numberOfRows: CGFloat
        if collectionView.numberOfItems(inSection: section) > Constants.maxNumberOfItemsInRow  {
            numberOfItems = CGFloat(Constants.maxNumberOfItemsInRow)
            numberOfRows = CGFloat(Constants.maxNumberOfRows)
        } else {
            numberOfItems = CGFloat(collectionView.numberOfItems(inSection: section))
            numberOfRows = CGFloat(Constants.minNumberOfRows)
        }


        let totalCellWidth = Constants.itemSize.width * numberOfItems
        let totalSpacingWidth = Constants.minimumInteritemSpacing * numberOfItems
        var leftInset = (collectionView.layer.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2

        let totalCellHeight = Constants.itemSize.height * numberOfRows
        let maximumSectionHeight = (Constants.itemSize.height * CGFloat(Constants.maxNumberOfRows)) + (CGFloat(Constants.maxNumberOfRows + 1) * Constants.minimumLineSpacing)

        if leftInset < 0.0 { leftInset = 0.0 }

        let topInset = (maximumSectionHeight - totalCellHeight) / 2

        let rightInset = leftInset

        return UIEdgeInsets(top: topInset, left: leftInset, bottom: topInset, right: rightInset)
    }

2 个答案:

答案 0 :(得分:1)

您可以使用此代码。

var arr = [{
  "name": "3",
  "iStart": "08:30:00",
},{
  "name": "5",
  "iStart": "09:30:00",
},{
  "name": "1",
  "iStart": "07:30:00",
},{
  "name": "2",
  "iStart": "07:30:03",
},{
  "name": "4",
  "iStart": "09:12:03",
}]

arr.sort(function(a,b){
  var c = parseInt( a.iStart.split(':').join('')) ;
  var d = parseInt( b.iStart.split(':').join('')) ;

  return c-d;
});

答案 1 :(得分:-1)

你可以从时间中删除“:”并转换为int,这样:

“08:30:00” - &gt; “083000” - &gt; 83000

将小于

“16:02:55” - &gt; “160255” - &gt; 160255

我认为你可以这样使用usort(假设你有json_decode'作为你的json字符串的PHP数组:)

function cmp($a, $b){
  // [...] make sure $a['iStart'] exists with isset()
  $a = (int)str_replace(':', '', $a['iStart']); // convert "08:30:00" to 83,000
  $b = (int)str_replace(':', '', $b['iStart']);
  if ($a == $b) {
      return 0;
  }
  return ($a < $b) ? -1 : 1;
}

usort($yourJsonDecoded, "cmp");

参考usort() http://php.net/manual/fr/function.usort.php

PS:如果您还想考虑日期,请删除“ - ”:

$a = (int) (str_replace('-', '', $a['iDate']) . str_replace(':', '', $a['iStart']))

这将执行以下操作:“2017-05-21”和“08:30:00” - &gt; 20,170,821,083,000