Reputation: 343
Is there any alternative ways which are more shorter and beautiful? Currently using the Maatwebsite/Laravel-Excel
foreach ($rows as $key => $value)
{
if($value->{'red'} == 1)
{
DB::table('furnitures')->insert(
[
'chair' => $value->{'Chair Name'},
'desk' => $value->{'Desk Name'},
'tv' => $value->{'TV Name'},
'lamp' => $value->{'Lamp Name'}
'carpet' => 1,
]);
}
if($value->{'green'} == 1)
{
DB::table('furnitures')->insert(
[
'chair' => $value->{'Chair Name'},
'desk' => $value->{'Desk Name'},
'tv' => $value->{'TV Name'},
'lamp' => $value->{'Lamp Name'}
'carpet' => 2,
]);
}
if($value->{'blue'} == 1)
{
DB::table('furnitures')->insert(
[
'chair' => $value->{'Chair Name'},
'desk' => $value->{'Desk Name'},
'tv' => $value->{'TV Name'},
'lamp' => $value->{'Lamp Name'}
'carpet' => 3,
]);
}
}
Notice the 'carpet' changes value according to the colors (red, green, blue). You must be asking "why all conditions are if, why not else if?" Its because i wanted to store all the values with different 'carpet' value althought all the other value is same
Upvotes: 1
Views: 57
Reputation: 2945
please try something like this :
$colors = ['red' => 1, 'green' => 2, 'blue' => 3];
foreach ($rows as $key => $value) {
foreach ($colors as $color_name => $color_value) {
if ($value->{$color_name} == 1) {
DB::table('furnitures')->insert(
[
'chair' => $value->{'Chair Name'},
'desk' => $value->{'Desk Name'},
'tv' => $value->{'TV Name'},
'lamp' => $value->{'Lamp Name'},
'carpet' => $color_value,
]
);
}
}
}
Upvotes: 1