To solve you issue you need to loop the result from the query and create a new array with the desired format [{name'=>'Email','type'=>'column','data'=>['1,2,3,4']}, {...}]
. There are several ways of solving this but I will describe a simple algorithm so you understand what to do.
$mysqlResult = [["name" => "Email", "data" => "16"],
["name" => "Web", "data" => "17"],
["name" => "Email", "data" => "23"]];
$expectedResult = [];
/*First we loop the mysql result mapping it to a dictionary where the keys of the dictionary is the `name`. This way we will be able to append all the `data` column values*/
foreach($mysqlResult as $result) {
$key = $result['name'];
/*We verify if the key does not exists already in expected result array. If the key does not exists we add it do the expected array.*/
if(!array_key_exists($key, $expectedResult)) {
$expectedResult[$key] = ['name' => $result['name'], 'type'=> 'column'];
}
/*We push the data column value to the data field that is going to store columns data.*/
$expectedResult[$key]['data'][] = $result['data'];
}
print_r($expectedResult);
The code above give us the following result:
Array
(
[Email] => Array
(
[name] => Email
[type] => column
[data] => Array
(
[0] => 16
[1] => 23
)
)
[Web] => Array
(
[name] => Web
[type] => column
[data] => Array
(
[0] => 17
)
)
)
Note that the field data
is an array of elements and we want it to be an array with a single string separating all the elements by a comma like this['1,2,3,4']. To achieve that we loop the dictionary using the PHP implode function:
foreach ($expectedResult as $key => $value) {
$expectedResult[$key]['data'] = [implode (',', $expectedResult[$key]['data'])];
}
Now we just need to extract the values from the expected result since it is a dictionary:
$expectedResult = array_values($expectedResult);
print_r($expectedResult);
The code above will create the expected array format you described:
Array
(
[0] => Array
(
[name] => Email
[type] => column
[data] => Array
(
[0] => 16,23
)
)
[1] => Array
(
[name] => Web
[type] => column
[data] => Array
(
[0] => 17
)
)
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…