php - Paypal api 将产品插入数组

标签 php arrays loops paypal

我可以使用循环在数组中插入产品吗 例子

这里我必须使用循环来添加购物车的产品

$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
    ->setCurrency('USD')
    ->setQuantity(1)
    ->setPrice('7.50');

$item2 = new Item();
$item2->setName('Granola bars')
    ->setCurrency('USD')
    ->setQuantity(5)
    ->setPrice('2.00');

这必须是所有项目的列表

$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));

所以我必须先使用循环将其添加到数组中 谢谢

最佳答案

你可以像这样将所有项目放在一个数组中(例如,使用索引计数器 $_index):

$items = array();
$index = 1;
$items[$index] = new Item();
$items[$index]->setName('Ground Coffee 40 oz')
              ->setCurrency('USD')
              ->setQuantity(1)
              ->setPrice('7.50');
$index = 2;
$items[$index] = new Item();
$items[$index]->setName('Granola bars')
              ->setCurrency('USD')
              ->setQuantity(5)
              ->setPrice('2.00');

这也可以在循环中完成:

$items = array();
$index = 0;
foreach ($object_array_with_items as $_item) {
   $index++;
   $items[$index] = new Item();
   $items[$index]->setName($_item['name_key'])
                 ->setCurrency($_item['currency_key'])
                 ->setQuantity($_item['quantity_key'])
                 ->setPrice($_item['price_key']);
}

然后你可以做

$itemList = new ItemList();
$itemList->setItems($items);

我希望这能回答您的问题。

关于php - Paypal api 将产品插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25990977/

相关文章:

php - 检查数据库、返回消息和发送电子邮件的函数

PHP 无法将全局变量导入到类内部的函数中

php - 添加价格和库存后如何在不重复产品的情况下获取数据

c - 如何在 C99 中声明另一个文件中定义的全局数组大小?

javascript - 如何从输入数组中获取多维数组

php - MySql语法错误,插入

javascript - angularjs 会自动创建嵌套结构吗?

Python:计算循环中日期时间对象之间的差异

javascript - PHP for-each 循环不起作用?

php和mysql foreach只显示第一条记录四次