Hello to all my dear friends
I have a result set from a MySQL database from a multi-table join that contains a lot of duplicate data (not duplicate rows)
and my goal is to convert this result set into a summarized form.
(to be able to create a loop and display its data on the client side in a simpler way)
I would be grateful if you could guide me on the best way to do this.
- Should I optimize the database query?
- Is it better to do this summarization on the server side and by PHP?
- Or is it better to do this on the client side using JavaScript?
my result set :
$result = array(
0=>array('username'=>'jack','ordercode'=>1,'productName'=>'x'),
1=>array('username'=>'jack','ordercode'=>1,'productName'=>'y'),
2=>array('username'=>'jack','ordercode'=>2,'productName'=>'z'),
3=>array('username'=>'steven','ordercode'=>3,'productName'=>'g'),
4=>array('username'=>'steven','ordercode'=>3,'productName'=>'j'),
);
and my ideal result set :
$result = array(
0=>array(
'username'=>array(
'jack'=>array(
'ordername'=>array(
'1'=>array(
'x','y'
),'2'=>array(
'z'
)
)
),'steven'=>array(
'ordername'=>array(
'3'=>array(
'g','j'
)
)
)
))
);
CodePudding user response:
You can use a simple foreach
like:
$result = [
['username' => 'jack', 'ordercode' => 1, 'productName' => 'x'],
['username' => 'jack', 'ordercode' => 1, 'productName' => 'y'],
['username' => 'jack', 'ordercode' => 2, 'productName' => 'z'],
['username' => 'steven', 'ordercode' => 3, 'productName' => 'g'],
['username' => 'steven', 'ordercode' => 3, 'productName' => 'j'],
];
$final = [];
foreach($result as $arr) {
$final['username'][$arr['username']]['ordername'][$arr['ordercode']][] = $arr['productName'];
}
print_r($final);
Result:
Array
(
[username] => Array
(
[jack] => Array
(
[ordername] => Array
(
[1] => Array
(
[0] => x
[1] => y
)
[2] => Array
(
[0] => z
)
)
)
[steven] => Array
(
[ordername] => Array
(
[3] => Array
(
[0] => g
[1] => j
)
)
)
)
)
Reference: