当我运行此代码时:
$yearRes=DB::table('order')
->select(DB::raw("year(created_at) as y"))
->orderBy("created_at")
->groupBy(DB::raw("year(created_at)"))->get();
foreach ($yearRes as $key => $value) {
$totalOrder[]=DB::table('order')->select(DB::raw("year(created_at) as y,sum(item_price) as p,count(id) as i"))->whereYear('created_at', '=', $value->y)->get();
}
它告诉我这个:
[[{"y":2016,"p":15050,"i":11}],[{"y":2017,"p":8440,"i":3}]]
当我运行此代码时
$abc=json_encode($totalOrder);
$a=rtrim($abc);
$title=explode('[', $a);
$c=implode('', $title);
$ac=rtrim($c,']');
......结果如下:
{"y":2016,"p":15050,"i":11}],{"y":2017,"p":8440,"i":3}
但我希望输出看起来像这样:
{"y":2016,"p":15050,"i":11},{"y":2017,"p":8440,"i":3}
我的代码出了什么问题?
答案 0 :(得分:0)
这将对您有所帮助:
echo trim(json_encode(array_column($totalOrder, 0)), '[]');
答案 1 :(得分:0)
最重要的是您想要对输出做什么和/或希望访问输出的位置和方式;看起来不那么无关紧要
答案 2 :(得分:-1)
你不需要所有rtrim
。你正在做的是一个黑客,而不是一个真正的解决方案。
您需要做的是在foreach中的代码上附加->first()
,例如:
$yearRes=DB::table('order')
->select(DB::raw("year(created_at) as y"))
->orderBy("created_at")
->groupBy(DB::raw("year(created_at)"))->get();
foreach ($yearRes as $key => $value) {
$totalOrder[]=DB::table('order')->select(DB::raw("year(created_at) as y,sum(item_price) as p,count(id) as i"))->whereYear('created_at', '=', $value->y)->get()->first();
}
然后您可以删除rtrims
和其他不必要的行。只需保留第一行
$abc=json_encode($totalOrder);