I am creating an array for an order to then pass this data to stripe, the array has multiple forEach clauses.
The issue I am facing is, if the order item(s) does not have menu_options it is not included in the array.
What am I doing wrong to ensure that each $orderItem is in the array wether it does or does not have an $itemOption / menu_options.
private function convertCartToOrderLines($order)
{
$lines = [];
foreach ($order->getOrderMenusWithOptions() as $orderItem) {
foreach ($orderItem->menu_options as $itemOptionGroup ) {
$itemOptionGroup = $orderItem->menu_options->groupBy('order_option_category');
foreach ($itemOptionGroup as $itemOptionGroupName => $itemOptions) {
foreach ($itemOptions as $itemOption) {
$test1 = "Qty: x".$orderItem->quantity." | ".$itemOption->order_option_name;
array_push($lines, [
'price_data' => [
'currency' => currency()->getUserCurrency(),
'unit_amount_decimal' => number_format($orderItem->subtotal, 2, '.', '') * 100,
'product_data' => [
'name' => $orderItem->name,
'description' => $test1,
],
],
'quantity' => 1,
]);
}
}
}
}
return $lines;
}
2
Answers
instead of
E.g.
Since menu_options is used only to get post descriptions, you can output this part to the post_description variable
If the post does not have menu_options, the description of the post will be an empty line, you need to consider whether this is a required field
This should work
You’ll need to intercept your empty order items and structure the entry as you see fit for the result array. You could write
continue
at the end of theif
block, but theforeach()
on themenu_options
won’t be entered anyhow.I’ve also move unchanging variable declarations up and out of loops to remove unnecessary iterative work for PHP (
$currency
and$subtotal
).This script should successfully populate the result array with empty order items and individual order option items.