【问题标题】:Add to each array element another element php向每个数组元素添加另一个元素php
【发布时间】: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


    【解决方案1】:

    要实现[{id: 1, quantity: 3}]会有几个想法,但它似乎是一个arrayList,所以下面是如何在PHP中创建一个arrayList。我没有测试代码,只是写在这里,但应该给你实现这个的想法。

    我正在考虑一个是 Order 类。

     <?php
    class Order {
            private $id;
            private $quantity;
        
            public function setId(int $id) {
                $this->id = $id;
                return $this;
            }
        
            public function getId(){
                return $this->id;
            }
        
            public function setQuantity(int $quantity) {
                $this->quantity  = $quantity;
                return $this;
            }
        
            public function getQuantity(){
                return $this-> quantity;
            }
        
            public function toArray(){
               return [
                   'id' => $this->getId(),
                   'quantity' => $this->getQuantity()
               ];
            }
        }
    ?>
    

    另一个是 OrderList。

    <?php
    class OrderList {
           private $orderList;
        
           public function __construct(Order ...$orders) {
                $this->orderList = $orders;
           }
         
           public function toArray(){
              $arr = [];
              foreach ($this->orderList as $order) {
                $arr[] = $order->toArray();
              }
              return $arr;
           }
        }
    ?>
    

    然后用like

    $order1 = new Order();
    $order1 = $order1->setId(1)->setQuantity(10);
    $order2 = new Order();
    $order2 = $order1->setId(2)->setQuantity(20);
        
    $orderList = new OrderList($order1, $order2);
    var_dump(json_encode($orderList->toArray()));
    

    //输出

    string(47) "[{"id":2,"quantity":20},{"id":2,"quantity":20}]"
    

    你不需要json_encode,我添加了它只用于打印。

    【讨论】:

      【解决方案2】:

      没关系,解决了->

              $prodsfinal = array();
          for ($i = 0; $i < sizeof($cantidades); $i++) {
              $array = [
                  'id' => json_decode($input['productos'][$i]),
                  'cantidad' => (int) $cantidades[$i],
              ];
              array_push($prodsfinal, $array);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-20
        • 2015-08-15
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2014-07-07
        相关资源
        最近更新 更多