将值数组添加到现有数组
Adding an array of values to an existing array
我有一个 foreach,我根据从我的表单中提交的选定复选框(它们是 `checkbox[$id]。所以我最终得到:
其中 1、2 和 3 是表单中提交的 ID。到目前为止一切顺利。
现在我的表单中也有一个输入字段 amount[$id]
。选择复选框时,我可以为该行输入一个金额并提交结果。如果 id,我需要将 amount
的值添加到我的数组中。我的最终结果应该是这样的:
[1 => ['amount' => '10'], 2 => ['amount' => '12'], 3 => ['amount' => '5'] // And so on
我尝试合并,array_push,但我似乎做错了,因为我无法弄清楚。有什么指点吗?
像这样的东西应该可以工作:
$result = [];
$ids = [1,2,3]; // I suppose it is `$_POST['ids']`
$amounts = [1 => 10, 2 => 11, 3 => 22]; // I suppose it is `$_POST['amount']`
foreach ($ids as $id) {
if (!empty($amounts[$id])) {
$result[$id] = ['amount' => $amounts[$id]];
}
}
仅当数组大小相等时,才能按照评论中的建议使用 array_combine
。所以如果你有类似的东西:
$ids = [1,2,4];
$amounts = [1 => 10, 2 => 11, 3 => 0, 4 => 22];
print_r(array_combine($ids, $amounts)); // PHP Warning
第二个事实 - array_combine
不会将值创建为数组。所以
$ids = [1,2,3];
$amounts = [1 => 10, 2 => 11, 3 => 10];
print_r(array_combine($ids, $amounts)); // no subarrays here
我有一个 foreach,我根据从我的表单中提交的选定复选框(它们是 `checkbox[$id]。所以我最终得到:
其中 1、2 和 3 是表单中提交的 ID。到目前为止一切顺利。
现在我的表单中也有一个输入字段 amount[$id]
。选择复选框时,我可以为该行输入一个金额并提交结果。如果 id,我需要将 amount
的值添加到我的数组中。我的最终结果应该是这样的:
[1 => ['amount' => '10'], 2 => ['amount' => '12'], 3 => ['amount' => '5'] // And so on
我尝试合并,array_push,但我似乎做错了,因为我无法弄清楚。有什么指点吗?
像这样的东西应该可以工作:
$result = [];
$ids = [1,2,3]; // I suppose it is `$_POST['ids']`
$amounts = [1 => 10, 2 => 11, 3 => 22]; // I suppose it is `$_POST['amount']`
foreach ($ids as $id) {
if (!empty($amounts[$id])) {
$result[$id] = ['amount' => $amounts[$id]];
}
}
仅当数组大小相等时,才能按照评论中的建议使用 array_combine
。所以如果你有类似的东西:
$ids = [1,2,4];
$amounts = [1 => 10, 2 => 11, 3 => 0, 4 => 22];
print_r(array_combine($ids, $amounts)); // PHP Warning
第二个事实 - array_combine
不会将值创建为数组。所以
$ids = [1,2,3];
$amounts = [1 => 10, 2 => 11, 3 => 10];
print_r(array_combine($ids, $amounts)); // no subarrays here