Hi I am a C# developer and currently working a bit in PHP. I know this is a very simple task but I really don't have an idea for this. I have to create a list with the items to be dynamically created with foreach loop. These are the static list items that I want to create list dynamically with foreach loop.
$item_1 = new Item();
$item_1->setName('Item 1')
->setCurrency('USD')
->setQuantity(2)
->setPrice('15');
$item_2 = new Item();
$item_2->setName('Item 2')
->setCurrency('USD')
->setQuantity(4)
->setPrice('7');
$item_3 = new Item();
$item_3->setName('Item 3')
->setCurrency('USD')
->setQuantity(1)
->setPrice('20');
// add item to list
$item_list = new ItemList();
$item_list->setItems(array($item_1, $item_2, $item_3));
$items = array();
for ($i = 1; $i <= SOME_NUMBER; $i++)
{
$item = new Item();
$item->setName('Item ' . $i);
// ...
$items[] = $item;
}
// ...
$itemList->setItems($items);
Use array for that:
$totalItems = 3;
$itemsList = new ItemsList();
$items = array();
for ($i = 1; $i <= $totalItems; $i++) {
$items[$i] = new Item();
$items[$i]->setName("Item{$i}"); // Or "Item".$i; " - means PHP will search for variable inside (either with "{}" or without). ' - means PHP will ignore variables
$items[$i]->setCurrency('USD');
/* If all methods returns Item object, than you can chine methods calls: */
$item[$i] = new Item();
$item[$i]
->setName("Item{$i}")
->setCurrency('USD')
->setQuantity($this->getQuantity());
}
$itemsList->setItems($items);
$item_list = array();
foreach($data as $value){
$item =new stdClass;
$item->name = $value->name;
$item->price = $value->price;
$item->quantity = $value->quantity;
$item->currancy = $value->currancy;
$item_list[] = $item;
}