【问题标题】:Sort by timestamp, then set certain elements as first按时间戳排序,然后将某些元素设置为第一
【发布时间】:2021-03-11 16:21:58
【问题描述】:

鉴于这个集合:

$payments = [{
    "timestamp": "2021-03-10 21:19:10",
    "amount": "100",
    "currency":"eur"
},
{
    "timestamp": "2021-03-10 22:11:10",
    "amount": "100",
    "currency":"gbp"
},
{
    "timestamp": "2021-03-10 23:19:10",
    "amount": "100",
    "currency":"usd"
},
{
    "timestamp": "2021-03-10 22:19:10",
    "amount": "100",
    "currency":"gbp"
}]

我想以付款按时间戳排序的方式对其进行排序,但从某种货币开始。例如 gbp

$payments = [{
    "timestamp": "2021-03-10 22:11:10",
    "amount": "100",
    "currency":"gbp"
},
{
    "timestamp": "2021-03-10 22:19:10",
    "amount": "100",
    "currency":"gbp"
}
{
    "timestamp": "2021-03-10 21:19:10",
    "amount": "100",
    "currency":"eur"
},
{
    "timestamp": "2021-03-10 23:19:10",
    "amount": "100",
    "currency":"usd"
}]

现在我正在以我首先采用货币为 gbp 的排序集合的方式进行操作,然后我将合并到货币为 not gbp 的排序集合。像这样:

$paymentsInSameCurrency = $payments
    ->where('currency',$currency)
    ->sortBy('timestamp');

$paymentsInDifferentCurrency = $payments
    ->where('currency','!=',$currency)
    ->sortBy('timestamp');

$payments = $paymentsInSameCurrency->merge($paymentsInDifferentCurrency);

有没有办法让它更有效率?

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    简化版可能是这样的:

     $payments = $payments
        ->sortByDesc(\DB::raw("currency = '$currency'")); // first when it's true
        ->sortBy('timestamp');                            // second level sorting by timestamp
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2020-04-24
      • 2016-11-07
      相关资源
      最近更新 更多