Php 按时间戳排序,然后将某些元素设置为第一个
鉴于此集合:Php 按时间戳排序,然后将某些元素设置为第一个,php,laravel,laravel-5,Php,Laravel,Laravel 5,鉴于此集合: $payments = [{ "timestamp": "2021-03-10 21:19:10", "amount": "100", "currency":"eur" }, { "timestamp": "2021-03-10 22:11:10", "amount"
$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的情况下进行排序收集,然后我将其合并到货币为而非gbp的排序收集。像这样:
$paymentsInSameCurrency = $payments
->where('currency',$currency)
->sortBy('timestamp');
$paymentsInDifferentCurrency = $payments
->where('currency','!=',$currency)
->sortBy('timestamp');
$payments = $paymentsInSameCurrency->merge($paymentsInDifferentCurrency);
有没有办法提高效率?简化版可以是这样的:
$payments=$payments
->sortByDesc(\DB::raw(“currency='$currency');//首先,当这是真的
->排序方式(“时间戳”);//按时间戳进行二级排序