Convert array to Google Charts format, adding dates that were the same.
I need to add title and count of the dates.
I edited the question, with the code I tried
Example:
$data = [
[
id => 1,
date => 2021-02-13 19:47:19
],
[
id => 2,
date => 2021-02-11 19:47:19
],
[
id => 3,
date => 2021-02-11 19:47:19
],
[
id => 4,
date => 2021-02-13 19:47:19
],
[
id => 5,
date => 2021-02-10 19:47:19
],
]
To:
$data = [
['Date', 'Orders'],
['13.02', 2],
['11.02', 2],
['10.02', 1]
]
i try:
foreach ( $views as $view ) {
$date = date( 'd-m-Y', strtotime( $view->post_date ) );
$date = DateTime::createFromFormat( 'd-m-Y', $date );
if ( array_key_exists( $date->format('d.m'), $days ) ) {
$days[$date->format('d.m')] = $days[$date->format('d.m')] + 1;
} else {
$days[$date->format('d.m')] = 1;
}
}
resulting in
Array ( [13.02] => 2
[12.02] => 3
[11.02] => 1
[09.02] => 1
)
My Answer:
1,
date = '2022-01-01',
title = 'Title 1',
count = 5
],
[
id = 2,
date = '2022-01-01',
title = 'Title 2',
count = 3
],
[
id = 3,
date = '2022-01-02',
title = 'Title 3',
count = 2
]
];
// Convert array to Google Charts format
$chartData = [];
foreach ($data as $item) {
$date = $item['date'];
$title = $item['title'];
$count = $item['count'];
if (!isset($chartData[$date])) {
$chartData[$date] = [];
}
$chartData[$date][] = [$title, $count];
}
// Add title and count of the dates
$finalChartData = [];
foreach ($chartData as $date => $values) {
$totalCount = 0;
foreach ($values as $value) {
$totalCount += $value[1];
}
$finalChartData[] = [$date, $totalCount];
}
// Output the final chart data
echo json_encode($finalChartData);
Rate this post
4 of 5 based on 3138 votesComments