2017-04-19 62 views
0

我有這個分頁程序實例返回:Laravel 5.3 - 將項目添加到分頁數據?

$products = 
{ 
    "products": 3, 
    "per_page": 10, 
    "current_page": 1, 
    "data": [ 
    { 
     "id": 4, 
     "product_type": "electronic", 
     "product_id": 6 
    }, 
    { 
     "id": 6, 
     "type": "electronic", 
     "product_id": 5 
    }, 
    { 
     "id": 9, 
     "type": "kitchen", 
     "product_id": 4 
    } 
    ] 
} 

我試圖將項目作爲第一項添加到data關鍵是這樣的:

$firstItem = { 
    "item": "should be first in data", 
    "code": 12345 
} 

最終的結果應該是這樣的:

$products = 
{ 
    "products": 3, 
    "per_page": 10, 
    "current_page": 1, 
    "data": [ 
    {         <- 
     "item": "should be first in data", <- 
     "code": 12345      <- 
    },         <- 
    { 
     "id": 4, 
     "product_type": "electronic", 
     "product_id": 6 
    }, 
    { 
     "id": 6, 
     "type": "electronic", 
     "product_id": 5 
    }, 
    { 
     "id": 9, 
     "type": "kitchen", 
     "product_id": 4 
    } 
    ] 
} 

我已經嘗試了很多方法,但都沒有得到結果。 任何想法如何完成最終結果?

+0

你有沒有嘗試一旦你分頁數據'array_unshift($ products ['data'],$ firstItem)'? – jfadich

+0

是的,這給了我'Illuminate \\ Pagination \\ LengthAwarePaginator超負荷元素的間接修改' – Wonka

+1

您需要從'LengthAwarePaginator'實例獲取數據作爲數組。嘗試做'$ products = $ products-> toArray()'然後執行我最初發布的代碼。 – jfadich

回答

1

如果您有分頁結果$products的實例,那麼你可以使用類似下面的前面加上一個新的項目爲數據,例如:

// Get the paginated data 
$products = \App\Product::paginate(10); 

// Create a new item and populate 
$item = new \StdClass; 
$item->item = "should be first in data"; 
$item->code = 12345; 

// Insert the new item at top 
$products->prepend($item); 

就是這樣。新的StdClass(不是一個雄辯的模型)項目將被置於頂部。

+1

'prepend'使它更容易。謝謝! – Wonka