【发布时间】:2021-03-20 01:23:10
【问题描述】:
我在逻辑领域还有一个问题。
我有一个包含 id 的数组:
$product_ids = ['1', '5', '3'];
我将另一个字符串转换为用逗号分隔的数组,这表示要提取的产品数量。例如,对于产品 1,我想要 3 个驱动器,因此我需要数组元素为“1,3”。
$finalarray = ["1,3", "5,2", "3,10"];
接下来我指出在控制器中执行的代码(我之前告诉过的代码在哪里):
public function ordenform(Request $request)
{
$input = $request->all();
$request->validate([
'nombre' => 'required|string',
'apellido' => 'required|string',
'productos' => 'required',
'cantidades' => 'required|string',
'enviosino' => 'required|in:si,no',
]);
// Quantity Array
$cantidades = explode(',', $input['cantidades']);
if (count($cantidades) != count($input['productos'])) {
return back()->withErrors(['Las cantidades no corresponden a los productos agregados']);
}
$total = 0;
$ganancia = 0;
foreach ($input['productos'] as $producto) {
$producto = Product::find((int) $producto);
$total += $producto->value;
$ganancia += $producto->ganancia;
$producto->stock = (int) $producto->stock - 1;
$producto->save();
}
if ($input['enviosino'] == 'si') {
$total += (int) $input['envio'];
}
if ($input['envio'] == null) {
$input['envio'] = 0;
}
// Products IDS Array
$jsonproductos = json_encode($input['productos']);
Order::create([
'nombre' => $input['nombre'],
'apellido' => $input['apellido'],
'product_ids' => $finalprods,
'value' => $total,
'ganancia' => $ganancia,
'envio' => $input['envio'],
]);
$caja = Config::where('id', 1)->get()->first();
$caja->dinerototal += $total;
$caja->gananciatotal += $ganancia;
$caja->save();
return back()->with('success', 'Orden creada correctamente');
}
最后,我需要将最终数组作为创建参数传递给 products_ids 列(稍后我将修改名称)。
我想到的另一个选择是将对象传递给数组:
[{id:1,数量:3}]
但我不知道如何创建该对象,我还是个新手,呵呵。
我希望我已经很好地解释了自己,英语不是我的母语。对不起。
我很关注你的 cmets !问候。
PS:我正在使用 Laravel
【问题讨论】:
标签: php arrays laravel sorting foreach