是否有一種優雅的方式從一個雄辯對象中刪除NULL值?我的對象與關係嵌套。這個特定的呼叫長度可能是1000行,所以我嘗試這樣做的主要原因是爲用戶節省帶寬,但服務器性能也是一個考慮因素。Laravel,從JSON中刪除null雄辯的對象屬性
我的代碼:
$data['locations'] = Location::with('address')->where('user_id', '1')->get();
return Response::json($data);
我嘗試過改變者,但除非我錯了存取器沒有權力的對象鍵,就值。
我也嘗試和失敗使用array_filter這樣的:
Any PHP function that will strip properties of an object that are null?
How to remove empty associative array entries
編輯根據要求,
{
"status": "ok",
"locations": [
{
"id": "1",
"latitude": "12.239107980271",
"longitude": "109.19479025725",
"user_time": "",
"transport": "Bus",
"title1": "",
"title2": "",
"address": {
"town": "Nha Trang",
"country": "Vietnam",
"address": "36-44 Hùng Vương, Lộc Thọ, Nha Trang, Khanh Hoa Province, Vietnam"
},
"altitude": {
"altitude": "10.006237983704"
},
"timezone": {
"offset": "25200"
},
"forecast": {
"icon": "",
"high_temp": "",
"low_temp": ""
}
},
{
"id": "2",
所需的響應:
{
"status": "ok",
"locations": [
{
"id": "1",
"latitude": "12.239107980271",
"longitude": "109.19479025725",
"transport": "Bus",
"address": {
"town": "Nha Trang",
"country": "Vietnam",
"address": "36-44 Hùng Vương, Lộc Thọ, Nha Trang, Khanh Hoa Province, Vietnam"
},
"altitude": {
"altitude": "10.006237983704"
},
"timezone": {
"offset": "25200"
}
},
{
"id": "2",
正如您所看到的,我可以簡單地遍歷整個過程並刪除任何鍵 - 或鍵的鍵 - 沒有值。我希望拉拉維爾能提供一個乾淨/快速的方式來做同樣的事情。
我應該補充說,技術上只有經緯度是必填字段!
發表一個你得到的和你想要的結果的例子。 – marcanuy 2014-09-05 18:02:46
已發佈樣本! – daviestar 2014-09-05 20:20:05