2014-09-23 55 views
0

浩我可以插入陣列產品的使用環路 例如貝寶API插入產品陣列

在這裏,我必須使用循環來添加購物車

$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)); 

,所以我必須使用循環中首先將其添加到陣列 謝謝

回答

2

您可以將所有項目放入數組中(例如,與索引計數器$ _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); 

我希望這回答您的題。

+0

讓我試試,我認爲它會工作:) – 2014-09-23 09:41:09

+0

錯誤MALFORMED_REQUEST :( – 2014-09-23 10:04:51

+0

是所用的餅乾也許大? – 2014-09-23 11:08:35

0

Erwin van Hoof幾乎是正確的,但缺少一個重要的細節。 Erwins解決方案將在數組層次結構中創建一個PayPal無法理解的索引。所以,如果你想像Erwin所建議的那樣做,那麼你將不得不創建第二個發送給PayPal的數組。我會做這樣的:

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

    $items[] = $item[$index]; 
} 

那麼這個作品,未經MALFORMED_REQUEST來自PayPal:

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

只是要在代碼中使用一點從@換個工作。

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