Steve Brown
Steve Brown

Reputation: 447

Laravel Loop through array

I stuck an something really easy (I guess).

I have an array:

array(30) { 
["gericht_1_mo"]=>
string(6) "Nudeln"
["preis_1_mo"]=>
string(4) "5,50"
["gericht_2_mo"]=>
string(64) "Paniertes Schweineschnitzel
mit Pommes frites und Beilagensalat"
["preis_2_mo"]=>
string(2) "13"
["gericht_1_di"]=>
string(75) "Gebratenes Hähnchenbrustfilet auf asiatischer Gemüsesoße mit Basmatireis"
["preis_1_di"]=>
string(4) "4,70"
["gericht_2_di"]=>
string(83) "Geröstete Hörnchennudeln mit Ei, Käse, Speck
und Zwiebeln dazu ein bunter Salat"
["preis_2_di"]=>
 string(4) "7,90"
}

and want to loop through the array in my view

@foreach($input as $key => $item)



    <div class="col-xs-6" style="width: 100%;">
        <h3>Day</h3>
        <hr />
        <div class="dishContainer">
          <h4 class="dishTitle">item</h4>
          <p class="dishDesc">{{ $item }}</p>
          <p class="priceTag">{{ How caN I display the Price of every item ?}}€</p>
        </div>
    </div>
    @endforeach

After a long time playing around I cant find the solution to output the data properly.

Upvotes: 0

Views: 1178

Answers (2)

John Doe
John Doe

Reputation: 876

   @for ($x = 0; $x < count($input); $x+=2)
          <div class="col-xs-6" style="width: 100%;">
          <h3>Day</h3>
          <hr />
          <div class="dishContainer">
                 <h4 class="dishTitle">item</h4>
                 <p class="dishDesc">{{ $input[$x] }}</p>
                 <p class="priceTag">{{ $input[$x+1] }}€</p>
                 </div>
          </div>
   @endfor    

Upvotes: 0

Daan Meijer
Daan Meijer

Reputation: 1348

I would argue there is something wrong with your data model. At least, in order to render the data as you would like, I would convert the data before calling the view. Something like:

$output = [];
foreach($input as $key => $value){
    if(preg_match('/(preis|gericht)_([0-9]+_[a-z]{2})/', $key, $matches)){
        $output[$matches[2]][$matches[1] = $value;
    }
}

Mind you, this code is unchecked, so it should probably be tested/corrected before use.

Upvotes: 1

Related Questions