我从MySQL
那里得到一份食物清单,我想基于相同的类别类型嵌套JSON
输出。
我有一个用PHP
编写的代码,我想转换为节点js。
function getAllFood($id){
$stmt = $this->con->prepare("SELECT food.food_id, food.food_name,
food_category.food_category, food.food_price, food.res_branch_id,
food.food_type, food.food_desc, food.food_image FROM food,
food_category WHERE food.res_branch_id = ? AND food.food_category
= food_category.id");
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($food_id, $food_name, $food_category, $food_price,
$res_branch_id, $food_type, $food_desc, $food_image);
$food = array();
while($stmt->fetch()){
$temp = array();
$temp['food_id'] = $food_id;
$temp['food_name'] = $food_name;
$temp['food_category'] = $food_category;
$temp['food_price'] = $food_price;
$temp['res_branch_id'] = $res_branch_id;
$temp['food_type'] = $food_type;
$temp['food_desc'] = $food_desc;
$temp['food_image'] = $food_image;
array_push($food, $temp);
}
$data = [];
foreach($food as $row){
$category = $row['food_category'];
if(!isset($data[$category])) {
$data[$category] = [
'title' => $category,
'section' => []
];
}
$data[$category]['section'][] = ['id' => $row['food_id'], 'name' => $row['food_name'], 'image' => $row['food_image'], 'desc' => $row['food_desc'], 'price' => $row['food_price'], 'res_branch_id' => $row['res_branch_id'], 'food_type' => $row['food_type']];
}
return array_values($data);
}
{
"data": [
{
"title": "Personal Pizza",
"section": [
{
"id": 1,
"name": "Tandoori Paneer",
"image": "phut_0.jpg",
"desc": "An all-indian fovourite made with paneer, tandoori marinade, onions and mozzarella cheese",
"price": "60.83",
"res_branch_id": 1,
"food_type": "Veg"
}
]
},
{
"title": "Medium Pizza",
"section": [
{
"id": 11,
"name": "Tandoori Paneer",
"image": "phut_0.jpg",
"desc": "An all-Indian favourite made with paneer, tandoori marinade, onions and mozzarella cheese.",
"price": "150",
"res_branch_id": 1,
"food_type": "Veg"
}
]
},
{
"title": "Large Pizza",
"section": [
{
"id": 17,
"name": "Giardino Feast",
"image": "phut_0.jpg",
"desc": "Go on a magical journey of veggies with jalapeno chillies, mushrooms, onions, corn baby corn and olives.",
"price": "200",
"res_branch_id": 1,
"food_type": "Veg, New"
}
]
}
]
}
我想将下面的代码片段转换为node.js
输出的MySQL
。
$data = [];
foreach($food as $row){
$category = $row['food_category'];
if(!isset($data[$category])) {
$data[$category] = [
'title' => $category,
'section' => []
];
}
$data[$category]['section'][] = ['id' => $row['food_id'], 'name' => $row['food_name'], 'image' => $row['food_image'], 'desc' => $row['food_desc'], 'price' => $row['food_price'], 'res_branch_id' => $row['res_branch_id'], 'food_type' => $row['food_type']];
}
在Node.js
下面的代码段中,我试图根据任务创建的日期来获取任务。请帮我转换以上逻辑。
router.get('/:user_id', checkAuth, (req,res,next) => {
const userId = req.params.user_id;
sql.query('SELECT * FROM task WHERE user_id = ?',[userId], (error, results, fields) => {
if(error) {
res.status(500).json({
message: 'sql error'
})
} else {
res.status(200).json({
task: results
})
}
})
})