2016-09-16 38 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