我使用 Input::all() 从动态生成的表单(我使用 jQuery 允许用户添加字段)中获取一些输入。字段名称为"first_names[]"、"last_names[]"和"电子邮件[]"。
$input变量现在如下所示:
array (size=4)
'_token' => string '3VCQFUmAx8BNbSrX9MqjGtQhYovOaqecRUQSAL2c' (length=40)
'first_names' =>
array (size=1)
0 => string 'John' (length=4),
1 => string 'Jane' (length=4)
'last_names' =>
array (size=1)
0 => string 'Doe' (length=3),
1 => string 'Doe' (length=3)
'emails' =>
array (size=1)
0 => string 'johndoe@example.com' (length=24),
0 => string 'janedoe@example.com' (length=24)
我想做的是从该输入创建一个数组,如下所示:
array (
0 => array(
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'johndoe@example.com'
),
1 => array(
'first_name' => 'Jane',
'last_name' => 'Doe',
'email' => 'janendoe@example.com'
)
)
有没有一种简单的方法可以做到这一点,而无需迭代每个数组并构建新数组?有没有更好的方法来生成输入?谢谢。
好的伙计们,在Laravel IRC中的alexrussell的帮助下,我们已经想通了。
第一件事是JS:
var delegateId = 0;
$('.add-delegate').click(function() {
$.get('/add-delegate/' + delegateId++, function(html) {
$(html).appendTo('#delegates');
});
});
$(document).on('click', '.remove-delegate', function() {
$(this).parent().parent().remove();
});
我们创建一个delegateId变量,将其附加到get请求URL,然后在我们的路由中.php我们执行以下操作:
Route::get('add-delegate/{id}', function($id) {
return View::make('admin.bookings.partials.add-delegate', compact('id'));
});
这会将 id 发送到我们用于生成表单字段的视图。然后以我们做的形式:
<div class="row-fluid">
<div class="span12">
<input type="text" name="delegates[{{ $id }}][first_name]" placeholder="First Name">
<input type="text" name="delegates[{{ $id }}][last_name]" placeholder="Last Name">
<input type="text" name="delegates[{{ $id }}][email]" placeholder="Email">
<label class="checkbox">
<input type="checkbox" name="delegates[{{ $id }}][prerequisites]"> Prerequisites
</label>
<button type="button" class="btn btn-danger remove-delegate">Remove</button>
</div>
</div>
一旦我们得到代表的输入,请使用:
Input::get('delegates')
然后,我们有一个很好的数组可以使用,这正是我们所追求的:
array (size=2)
0 =>
array (size=3)
'first_name' => string 'John' (length=4)
'last_name' => string 'Doe' (length=3)
'email' => string 'johndoe@example.com' (length=19)
1 =>
array (size=3)
'first_name' => string 'Jane' (length=4)
'last_name' => string 'Doe' (length=3)
'email' => string 'janedoe@example.com' (length=19)