簡體   English   中英

向每個數組元素添加另一個元素 php

[英]Add to each array element another element php

我在邏輯 realm 中還有一個問題。

我有一個包含 id 的數組:

$product_ids = ['1', '5', '3']; <- 示例

我將另一個字符串轉換為用逗號分隔的數組,這表示要提取的產品數量。 例如,對於產品 1,我想要 3 個驅動器,因此我需要數組元素為“1,3”。

$finalarray = ["1,3", "5,2", "3,10"];

接下來我指出在 controller 中執行的代碼(我之前所說的在哪里):

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}]

但我不知道如何創建 object,我還是個新手,呵呵。

我希望我已經很好地解釋了自己,英語不是我的母語。 對不起。

我很注意你的評論。! 問候。

PS:我使用的是 Laravel

沒關系,解決了->

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

要實現[{id: 1, quantity: 3}]會有幾個想法,但它似乎是一個 arrayList,所以下面是如何在 PHP 中創建一個 arrayList。 我沒有測試代碼,只是寫在這里,但應該給你實現這一點的想法。

我正在考慮訂購 class。

 <?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;
       }
    }
?>

然后像

$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,我已將其添加為僅用於打印。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM