0

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));
1
  • Do you know how to write a loop? Do you know how to work with arrays? What exactly are you stuck on with this? Where would the dynamic data come from? Commented Mar 5, 2015 at 11:45

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1
$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;
}

Comments

0
$items = array();

for ($i = 1; $i <= SOME_NUMBER; $i++)
{
    $item = new Item();
    $item->setName('Item ' . $i);
    // ...
    $items[] = $item;
}

// ...

$itemList->setItems($items);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.