Reputation: 17
I am making API request to Google sheets and I want to visualise data from table into chart but I can't manage to convert the response JSON into usable one for the chart. I want to get every row of the table in different array with the name of row and the contents of the row as shown bellow.
This is what I receive from the API:
Array
(
[0] => Array
(
[A] => 99.39%
[B] => 91.27%
[C] => 94.44%
)
[1] => Array
(
[A] => 49.19%
[B] => 19.25%
[C] => 62.11%
)
...........
)
And I want to transform it into this: I just want to separate every column. name: A, data: 99.39%, 49.19% .., then name: B, data: 1, 2 ......
series: [{
title: 'A',
data: ['99.39%', '49.19%']
}, {
title: 'B',
data: [.....]
}, {
title: 'C',
data: [.....]
}, {
....
}]
I tried to do it this way but it wasn't successfull:
foreach ($rawData as $subarray) {
$converted_subarray = array_map('floatval', $subarray);
$series[] = [
'name' => key($converted_subarray),
'data' => array_values($converted_subarray),
];
}
The result I got:
Array
(
[0] => Array
(
[name] => A
[data] => Array
(
[0] => 99.39%
[1] => 91.27%
[2] => 94.44%
)
)
[1] => Array
(
[name] => A
[data] => Array
(
[0] => 49.19%
[1] => 19.25%
[2] => 62.11%
)
)
.....
)
The main problem I have is that the 'name' value doesn't change to A, B, C ... but it stays A
Upvotes: 1
Views: 37
Reputation: 1944
This code will help you
<?php
$array = [
[
'A' => 12,
'B' => 13,
'C' => 14,
],
[
'A' => 15,
'B' => 16,
'C' => 17,
]
];
$keys = [];
foreach ($array as $element) {
foreach ($element as $key => $subElementValue) {
if (array_key_exists($key, $keys)) {
$keys[$key][] = $subElementValue;
} else {
$keys[$key] = [];
$keys[$key][] = $subElementValue;
}
}
}
print_r($keys);
output
Array
(
[A] => Array
(
[0] => 12
[1] => 15
)
[B] => Array
(
[0] => 13
[1] => 16
)
[C] => Array
(
[0] => 14
[1] => 17
)
)
This script iterate your array and just check and update the $key
array and then make the final array which is you mentioned in your question
Upvotes: 1