I have an array contains the dates of last 7 days, this array is created with o loop.
$now = new DateTime();
$startDate = $now->modify('-6 day');
$labels = [];
$data = [];
for ($i = 0; $i <= 6; $i++) {
$day = $startDate->modify('+1 day');
$labels[] = $day->format('Y-m-d');
}
and this is the output of $labels:
$labels = array:7 [▼
0 => "2023-07-05"
1 => "2023-07-06"
2 => "2023-07-07"
3 => "2023-07-08"
4 => "2023-07-09"
5 => "2023-07-10"
6 => "2023-07-11"
]
And I have a query to select number of views of an element (Property) in this dates.
This query can return 7 rows as it can return less than 7 or also 0 rows if there is not views in any of days.
In my case , I have visits only in the last two days and this is the output of result:
$result = array:2 [▼
0 => array:2 [▶
"numberViews" => 20
"dayDate" => "2023-07-10"
]
1 => array:2 [▶
"numberViews" => 32
"dayDate" => "2023-07-11"
]
]
What I’d like to do is to check each date in the first array if exists in the group of arrays returned by the query, if it doesn’t exist so it should be zero and make an array of data like so:
$data = [0,0,0,0,0,20,32]
2
Answers
First you need to initialize your $data array to have the same array-keys as your $labels array.
Now you can iterate your $result array and use the php function array_search to count the number of views.
You can do it in two simple steps:
$result
and replace0
with the number of views, for the dates present in$result
.You can combine step #1 into your existing code, to generate
$output
instead of$labels
(and you don’t need step #1 above any more):Check it online.