Laravel使每个对象成为一个数组

时间:2016-01-20 13:57:27

标签: php laravel

我收到了一个查询,它返回了对象。我想让每个对象成为一个数组:

这是我的问题:

$transactions['transactions'] = Transaction::groupBy(DB::raw('DATE(created_at)'))
      ->selectRaw('FLOOR(SUM(amount)) as total, DATE(created_at) as date')
      ->orderBy('created_at')
      ->get()->toArray;

以下是我得到的结果:

"transactions": [
  {
    "total": "88781",
    "date": "2015-01-01"
  },
  {
    "total": "95630",
    "date": "2015-01-02"
  },
  {
    "total": "57857",
    "date": "2015-01-03"
  },
  {
    "total": "85252",
    "date": "2015-01-04"
  },
  {
    "total": "64763",
    "date": "2015-01-05"
  }
]

预期结果:

 "transactions": [
  [
    "88781",
    "2015-01-01"
  ],
  [
    "95630",
    "2015-01-02"
  ],
  [
    "57857",
    "2015-01-03"
  ],
  [
    "85252",
    "2015-01-04"
  ],
  [
    "64763",
    "2015-01-05"
  ]
]

我试过json_decode但没有运气。

任何解决方案?

1 个答案:

答案 0 :(得分:2)

您可以尝试映射集合中的值并将它们转换为非关联数组:

$transactions_result = Transaction::groupBy(DB::raw('DATE(created_at)'))
      ->selectRaw('FLOOR(SUM(amount)) as total, DATE(created_at) as date')
      ->orderBy('created_at')
      ->get();

$transactions_result_as_array = $transactions_result->map(function($item, $key){
    return [$item->total, $item->date];
});

$transactions['transactions'] = $transactions_result_as_array->toArray();