简体   繁体   中英

Create Array Inside Foreach Loop

How to put these codes in a foreach loop?

    $item1_details = array(
        'id' => 'a1',
        'price' => 18000,
        'quantity' => 3,
        'name' => "Apple"
    );


    $item2_details = array(
        'id' => 'a2',
        'price' => 20000,
        'quantity' => 2,
        'name' => "Orange"
    );

Then the array above will be saved in a variable. It's an array. And, yes, I have no idea how to do a loop inside array. So please help me for this too.

    $item_details = array ($item1_details, $item2_details);

Thus, I have to questions. First, how to create an array inside a foreach loop. Second, How to loop inside an array.

You don't put a loop inside an array, you push onto the array in a loop.

$item_details = array();
for ($i = 0; $i < 10; $i++) {
    $item_details[] = $item1_details;
    $item_details[] = $item2_details;
}

This will make an array with 10 alternating copies of $item1_details and $item2_details .

You mentioned a foreach loop, but that's for looping over an array that already exists. You didn't show any array to loop over, so I'm not sure how it applies in this case.

   <?php 

    $item_details = array();
    for ($i = 0; $i < 10; $i++) {
        $item_details[] = $item1_details;
        print_r($item1_details);
        $item_details[] = $item2_details;
        print_r($item2_details);
    }

if you want any one value from array

   $item_details = array();
   for ($i = 0; $i < 10; $i++) {
        $item_details[] = $item1_details;
        print_r($item1_details['price']);
        $item_details[] = $item2_details;
        print_r($item2_details['price']);
    }

You can use array_values with array_merge

$f = array_merge(array_values($item1_details), array_values($item2_details));

Working example:- https://3v4l.org/fDM3N

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM