Php 合并每行中具有相同产品标识但不同样式标识的行
我在实现我想要的输出时遇到问题。我有一个包含产品id和样式id的表。每个产品包含1个或多个不同的样式。style_id列不能与任何行的组合相同 注意我想通过SQL查询或使用PHP代码来实现这个结果 产品风格Php 合并每行中具有相同产品标识但不同样式标识的行,php,sql,laravel-5.2,Php,Sql,Laravel 5.2,我在实现我想要的输出时遇到问题。我有一个包含产品id和样式id的表。每个产品包含1个或多个不同的样式。style_id列不能与任何行的组合相同 注意我想通过SQL查询或使用PHP代码来实现这个结果 产品风格 id product_id style_id 1 1 1 2 1 2 3 1 3 4 1 4 5
id product_id style_id
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
我想通过SQL查询或使用PHP代码来实现这个结果
Array[12][
{
"id": 1,
"name": "Product sample",
"description": "Sample",
"price": "11.00",
"level": "school",
"style_name":{[
"Style 1",
"Style 2",
"Style 3",
"Style 4"
]
}
"style_id": {[
1,
2,
3,
4,
]
},
"rank_id": 232
}
{
"id": 2,
"name": "Sample 2",
"description": "Sample 2",
"price": "10.00",
"level": "school",
"style_name": "Karate",
"style_id": 1,
"rank_id": 232
}
]
这是我的当前代码。
$grading_products= \DB::table('products as p')
->leftjoin('product_style as ps', 'p.id', '=', 'ps.product_id')
->join('style_users as su', 'ps.style_id', '=', 'su.style_id')
->join('styles as s', 'ps.style_id', '=', 's.id')
->whereRaw('su.user_id = ' .$id. ' AND p.product_type_id = 1 AND p.service_sub_type_id = 2')
->select('p.id', 'p.name', 'p.description', 'p.price', 'p.level', 'ps.product_id', 's.name as style_name', 'ps.style_id as ps_style', 'su.style_id', 'su.rank_id')
->get();
这是我当前的输出
Array[12][
{
"id": 1,
"name": "Product Sample",
"description": "Sample",
"price": "11.00",
"level": "school",
"style_name": "style 1",
"style_id": 1,
"rank_id": 232
},
{
"id": 1,
"name": "Product Sample",
"description": "Sample",
"price": "11.00",
"level": "school",
"style_name": "style 2",
"style_id": 2,
"rank_id": 232
}
{
"id": 2,
"name": "Sample 2",
"description": "Sample 2",
"price": "10.00",
"level": "school",
"style_name": "Karate",
"style_id": 1,
"rank_id": 232
},
]
注意我想通过SQL查询或使用PHP代码来实现这个结果。以当前输出为起点,这里有一个混乱的解决方案:
$new_output = [];
$keyed = [];
foreach ($current_output as $row) {
$keyed[$row['id']]['style_name'][] = $row['style_name'];
$keyed[$row['id']]['style_id'][] = $row['style_id'];
$keyed[$row['id']]['row'] = $row;
}
foreach ($keyed as $id => $data) {
$row = $data['row'];
$temp_output = [
'id' => $id,
'name' => $row['name'],
'description' => $row['description'],
'price' => $row['price'],
'level' => $row['level'],
];
if (count($keyed[$row['id']]['style_name']) > 1) {
$temp_output['style_name'] = $data['style_name'];
} else {
$temp_output['style_name'] = $data['style_name'][0];
}
if (count($keyed[$row['id']]['style_id']) > 1) {
$temp_output['style_id'] = $data['style_id'];
} else {
$temp_output['style_id'] = $data['style_id'][0];
}
$temp_output['rank_id'] = $row['rank_id'];
$new_output[] = $temp_output;
}
(未测试)数据库将为每个唯一组合提供一个新行。您必须遍历脚本中的结果才能创建要查找的数组。是的,它将为每个唯一的组合创建一个新行。这就是我寻求帮助的原因,我如何才能实现我想要的预期输出。看看GROUP_CONCAT: