2016-09-16 76 views
2

我想每一個循環任命並把它放在JSON這樣的:將數據循環到json中?

[ 
    { 
     "id":"1", 
     "title":"Test 1", 
     "start":"2016-09-16 12:00:00", 
     "end":"2016-09-16 14:00:00", 
     "allDay":false 
    }, 

    { 
     "id":"2", 
     "title":"Test 2", 
     "start":"2016-09-15 12:00:00", 
     "end":"2016-09-15 14:00:00", 
     "allDay":false 
    } 
] 

我有一個表appointments在數據庫中。

id | title | appointment_date_start | appointment_date_end | 
------------------------------------------------------------- 
1 | Test 1 | 2016-09-16 12:00:00 | 2016-09-16 14:00:00 | 
2 | Test 2 | 2016-09-15 12:00:00 | 2016-09-15 14:00:00 | 

在我的feed.blade.php我得到的所有數據。 所以我可以這樣做:

@foreach ($appointments as $appointments) 

    {{ $appointment->id }} 
    {{ $appointment->title }} 
    {{ $appointment->appointment_date_start }} 
    {{ $appointment->appointment_date_end }} 

@endforeach 

這將輸出數據庫中的數據。但是如何在數組中對它進行foreach?

$event_array[] = array(
    'id' => {{ $appointment->id }}, 
    'title' => {{ $appointment->gender }}, 
    'start' => {{ $appointment->appointment_date_start }}, 
    'end' => {{ $appointment->appointment_date_end }}, 
    'allDay' => false 
); 

編輯

我在公共職能試過這種

public function feed() 
{ 
    $feed = Appointment::all(); 
    return $feed->toJson(); 
    return view('appointments/feed'); 
} 

這是我得到

{ 
    id: 35, 
    user_id: 1, 
    gender: "men", 
    appointment_date_start: "2016-09-14 20:00:00", 
    appointment_date_end: "2016-09-14 20:40:00", 
    created_at: "2016-09-16 08:16:16", 
    updated_at: "2016-09-16 08:16:16" 
} 

我需要刪除gender, created_at and updated_at並且appointment_date_start應該是start並且appointment_date_end應該結束?這可能嗎?

回答

1

如果你想刪除created_at和的updated_at,只是不同時從數據庫中獲取的數據中選擇屬性:

$feed = Appointment::select('id', 'user_id', 'appointment_date_start as start', 'appointment_date_end as end')->get(); 
// leave created_at and updated_at 
// select('old as new') to change the attribute name 

則數組爲JSON與json_encode

return json_encode($feed); 
+0

是的,它有效,但是有沒有辦法從appoinment_date_start更改名稱來啓動? – twoam

1

你可以去{{ $appointments->toJson() }},那是你想要的嗎?

+0

編碼能你檢查我的編輯? – twoam

+0

我認爲你的問題是回答,是嗎? – jsphpl