I have data from a database that I want to convert to another format. The data is in the form of an array as below
$array = [
['type 1', 'Country 1', 243],
['type 1', 'Country 2', 500],
['type 1', 'Country 3', 400],
['type 2', 'Country 1', 234],
['type 2', 'Country 2', 1234],
['type 2', 'Country 3', 1400],
['type 3', 'Country 1', 222],
['type 3', 'Country 2', 25],
['type 3', 'Country 3', 120],
];
How to convert array above with php to array like this below:
$toArray = [
[
'name' => 'type 1',
'data' => [
[
'name' => 'Country 1',
'y' => 243
],
[
'name' => 'Country 2',
'y' => 500
],
[
'name' => 'Country 3',
'y' => 400
],
]
],
[
'name' => 'type 2',
'data' => [
[
'name' => 'Country 1',
'y' => 234
],
[
'name' => 'Country 2',
'y' => 1234
],
[
'name' => 'Country 3',
'y' => 1400
],
]
],
...
];
Code so far
$toArray = [];
foreach($models as $key => $model) {
$type = [ 'name' => $model->type, 'data' => [] ];
if(in_array($type, $toArray)) {
continue;
}
$toArray[] = $type;
}
I'm confuse about this, can someone guide me?