scsskid
February 19, 2021, 9:48pm
1
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
texnixe
February 19, 2021, 10:01pm
2
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?
scsskid
February 19, 2021, 11:38pm
3
thanks for the reply
you are absolutly right, I didnt make sense
I fixed the example hopefully
scsskid
February 20, 2021, 3:00pm
4
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();
}
}
],