I am working with the PayPal API and I am trying to add multiple items to my itemList. My problem is that to make the itemList work, the array needs multiples variables:
$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));
I am using a loop before, to set-up the items, which I am trying to gather into one variable:
$allItems = "$item1, $item2";
It doesn’t work and I think that the problem is the coma, which I believe is read as plain text, and not as a “technical” coma (I do not know the term).
Please find here the full code for more clarity:
for ($i = 0; $i < $_POST['totalItems']; $i++) {
$product = $_POST['product'. $i];
$quantity = $_POST['quantity'. $i];
$price = $_POST['price'. $i];
$n = $i + 1;
${'item'. $n} = new Item();
${'item'. $n}->setName($product)
->setCurrency('EUR')
->setQuantity($quantity)
->setPrice($price);
if ($i == 0) {
$allTheItems = ${'item'. $n};
} elseif ($i < $_POST['totalItems']) {
$allTheItems = $allTheItems .', '. ${'item'. $n};
}
}
// We create the basket with the list of each item
$itemList = new ItemList();
$itemList->setItems(array($allTheItems));
Thank you very much in advance for your help.
Marc
Advertisement
Answer
You are creating a string with a list of the items and not an array of items. I’ve rewritten the code to make this process simpler – no need for variable variables and just add each item in the loop to an overall list of items (using $allTheItems[]
)…
// Create empty array
$allTheItems =[];
for ($i = 0; $i < $_POST['totalItems']; $i++) {
// Create empty item for new data
$newItem = new Item();
// Add data to the temp item
$newItem->setName($_POST['product'. $i])
->setCurrency('EUR')
->setQuantity($_POST['quantity'. $i])
->setPrice($_POST['price'. $i]);
// Add temp item into list of items
$allTheItems[] = $newItem;
}
// We create the basket with the list of each item
$itemList = new ItemList();
$itemList->setItems($allTheItems);