2017-04-15 33 views
0

unneccesary陣列當我運行這段代碼:刪除在PHP

$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

問題不明確,您的預期輸出是什麼? – C2486

+1

你爲什麼認爲這些是「不必要的數組」?你打算如何使用這些數據? – walther

回答

-1

你並不需要所有那些rtrim。你所做的只是一種破解而不是真正的解決方案。

你需要做的是追加->first()上的foreach中的代碼,在這樣的:

$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); 
0

這將幫助你:

echo trim(json_encode(array_column($totalOrder, 0)), '[]'); 
0

最重要的是你想要的與輸出做和/或在何處以及如何希望訪問的輸出;它看起來像不太相關