I have a JSON file like that
{
"20":{
"0":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"1":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"2":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"3":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"4":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"5":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"6":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
}
},
"21":{
"0":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"1":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"2":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"3":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"4":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"5":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
},
"6":{
"period":[
{
"open": 350,
"close": 600
},
{
"open": 660,
"close": 900
}
]
}
}
and I have an action
that is is decoding this JSON
to array, and pass with foreach
-es step by step, get that data and then store it in Database.
One guy said me that it is possible to refactor all that action, so I will not have absolutely (or approximative) any foreach or if. Also he said that it is called representative/functional
programming.
So, I found that concept and all that stuff, but also can't figure out how to do it.
My imperial
code:
$processingFile = file_get_contents(storage_path('hours.txt'));
$decodedFile = json_decode($processingFile, true);
$data = [];
$i = 0;
$batch = 10000;
foreach ($decodedFile as $business => $days) {
foreach ($days as $dayOfWeek => $periods) {
if (count($periods)) {
foreach ($periods['period'] as $key => $value) {
$i++;
$tmp = [
'business_id' => $business,
'day_of_week' => $dayOfWeek,
'open_periods_mins' => $value['open'],
'close_periods_mins' => $value['close'],
];
array_push($data, $tmp);
if($i === $batch) {
BusinessHour::insert($data);
$data = [];
$i = 0;
}
}
}
}
}
if( count($data) ) {
BusinessHour::insert($data);
}
I don't know how to parse
step by step and cut it all in functions using Laravel Collections
or whatever... declarative paradigm
.
Can someone explain / rewrite that code for teaching purpose? Thanks!