3 years ago

So I have an issue with nested foreach loops..

Posted 3 years ago by splaq

Ok, I have an array in the following format..

$someVar = [1,2,3,4,5,6,7];


$someVar1 = [ variable array elements, some null, some not ];

This is my current code for looping through those particular arrays..

// Save the record.

        // Now input the product sold and the quantity into the pivot table..
        foreach( $sales['product_id'] as $product_id ){
            foreach( $sales['cookies'] as $cookie_qty ) {
                if( !empty($cookie_qty ) ){
                    $invoice->products()->attach( $product_id, ['qty_sold' => $cookie_qty] );

$cookie_qty could be a value or it could be null $product_id will always return a value..

Now, I have tried variations of that nested foreach loop, but it still ends up the same. If I loop through the cookie quantity first, it checks if it's empty or not, if not goes into the product id loop, does it's business comes back out, checks the next cookie quantity, if that's null it skips it, goes to the next, checks it, if it's a value it goes into the product id loop and starts that loop all over again. Product id always ends up as 1. It resets every time. If It's in the configuration it is above, It goes directly into the cookie quantity loop, checks if it's empty, if not does it's business, comes back out, goes into cookie quantity again immediately, It goes back into cookie quantity which is then reset and at it's first value again, if the first was null then the next filled value becomes the first value, it repeats, never moves on to the next. I have tried inserting a break command(?) not sure if I'm referring to that correctly it's 4am. Either way I've tried to do that but still end up with one or the other arrays resetting. I'm lost. Again..

Please sign in or create an account to participate in this conversation.