Mar 3, 2023
0
Level 1
Last value missing in foreach loop
Hello i have this foreach loop that gets 2 dates one date value is generated by computer and other is from database the logic is when i insert a startdate and enddate the code has to generate the dates between date A and date B and check if each date exists in the database else give a value 0. The problem is that if i insert startdate and enddate values like :
startdate: 14.02.2023
enddate: 27.02.2023
the value 27.02.2023 will not be generated by the code, this is the code i have done so far:
$dateRanges = CarbonPeriod::create($dateFrom, $dateTo);
foreach ($dateRanges as $dateRange) {
$formattedDate = date("d-m-Y", strtotime($dateRange->toString()));
$outlayExist = false;
foreach ($outlays as $outlay) {
if ($outlay->date == $formattedDate) {
$outlaysWithZeroValues[] = $outlay;
$outlayExist = true;
break;
}
}
if (!$outlayExist) {
$outlaysWithZeroValues [] = (object) [
"currency" => serialize([
"ALL" => "0",
"USD" => "0",
"GBP" => "0",
"EUR" => "0",
]),
"date" => $formattedDate
];
}
}
return response()->json([
'message' => 'Success',
'data' => OutlayResource::collection($outlaysWithZeroValues)
], 200);
}
This is the json result i get
{
"message": "Success",
"data": [
{
"currencies": {
"ALL": 289
},
"date": "14-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "15-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "16-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "17-02-2023"
},
{
"currencies": {
"USD": 100
},
"date": "18-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "19-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "20-02-2023"
},
{
"currencies": {
"ALL": 300,
"USD": 250
},
"date": "21-02-2023"
},
{
"currencies": {
"ALL": 130,
"USD": 200
},
"date": "22-02-2023"
},
{
"currencies": {
"USD": 200
},
"date": "23-02-2023"
},
{
"currencies": {
"ALL": 1000,
"EUR": 2000,
"GBP": 500
},
"date": "24-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "25-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "26-02-2023"
},
{
"currencies": {
"ALL": 0,
"USD": 0,
"GBP": 0,
"EUR": 0
},
"date": "27-02-2023" //date 27 has values but comes 0
}
]
}
Please or to participate in this conversation.