我在实现我想要的输出时遇到了问题。我有一个包含product_id和style_id的表。每个产品包含1种或许多不同的样式。 style_id列不能与任何行相同。
注意我希望通过 SQL 查询或使用 PHP 代码。
product_style
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 代码。
答案 0 :(得分:0)
使用当前输出作为起点,这是一个混乱的解决方案:
$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;
}
(未经测试)