[Merx Plugin] bulk add predefined items

after trying to solve this with multiple foreach loops I still cant figure out how to map $arr to $arr_mapped

I need to explode the keys of $arr to get an element with up to three new keys to create $arr_mapped


<?php

$arr = [
  'abc:quantity' => 1,
  'abc:variant' => 'blue',
  'xyz:quantity' => 2,
  'foo:quantity' => null
];

$arr_mapped = [
  [
    'id' => 'abc',
    'quantity' => 1,
    'variant' => 'blue'
  ],
  [
    'id' => 'xyz',
    'quantity' => 2
  ]
];

background: I want to let a user bulk add predefined shopping items in a <form>
I’m Using the Kirby Merx Shop Plugin


<form>

<input name="abc:quantity" value="1">
<input name="abc:variant" value="blue">
<input name="xyz:quantity" value="2">
<input name="foo:quantity" value="">

<button>Submit</button>
</form>

thanks for any suggestions

I don’t really see the relation between the first and the second array. Where does green come from and what has happened to the value 2 for xyz? And where does the quantity for the abc:variant blue come from?

thanks for the reply

you are absolutly right, I didnt make sense
I fixed the example hopefully

I solved it with further help and the array_reduce fn

  [
      'pattern' => 'add-collection',
      'method' => 'post',
      'action' => function () {
        $formData = get();
        $reducer = function ($carry, $item) use ($formData) {
          [$id, $field] = explode(':', $item);
          $carry[$id]['id'] = $id;
          $carry[$id][$field] = $formData[$item];

          return $carry;
        };

        $arr_reduced = array_reduce(array_keys($formData), $reducer, []);
        $itemsToAdd = array_values($arr_reduced);

        try {
          foreach($itemsToAdd as $item) {
            $id = $item['id'];
            $quantity = floatval($item['quantity']);
            $variant = array_key_exists('variant', $item) ? $item['variant'] : '';
            $existingCartItem = cart()->find($id);

            if ($quantity) {
              if ($existingCartItem) {
                merx()->setMessage('Quantity Updated.');
                $quantity = $existingCartItem['quantity'] + $quantity;
              }
              cart()->add([
                'id' => $id,
                'quantity' => $quantity,
                'variant' => $variant,
              ]);
            }
          }
          go($_SERVER["HTTP_REFERER"]);
        } catch (Exception $ex) {
          return $ex->getMessage();
        }
      }
    ],