我是 php 的新手,我试图获取从以下响应中获得的数据,但我想将此数据设置在子数组中。这该怎么做?我有两个不同的表 category
和 Product
。如何明智地显示多个产品类别。
提前致谢!
{
"data" : [
{
"id" : "1",
"recipe_name" : "Tofu Tikka",
"ingredients" : "Firm tofu 1 pack (bite sized cube)\r\n",
"prepration" : "Press tofu with the help of plate to remove moisture
and leave for 30-40 minutes, then cut in cubes.\r\n",
"category_id":"1",
"category_name":"Today's Menu"
}
]
}
如何像下面这样在子数组中设置上面的响应
{
"data":[
"category_id":"1",
"category_name":"Today's Menu"
"recipes::[
{
"id":"1",
"recipe_name":"Tofu Tikka",
"ingredients":"Firm tofu 1 pack ",
"prepration":"Press tofu with the help of plate"
}, {
"id":"2",
"recipe_name":"Tikka Paneer",
"ingredients":"Firm tofu 1 pack ",
"prepration":"Press tofu with the help of plate"
},
]
]
}
下面是我的 PHP 文件
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// include database and object files
include_once '../config/database.php';
include_once '../objects/product.php';
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
// initialize object
$product = new Product($db);
// query products
$stmt = $product->read();
$num = $stmt->rowCount();
// check if more than 0 record found
if ($num>0) {
// products array
$products_arr=array();
$products_arr["data"]=array();
// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// extract row
// this will make $row['name'] to
// just $name only
extract($row);
$product_item=array(
"id" => $id,
"recipe_name" => $recipe_name,
"ingredients" => html_entity_decode($ingredients),
"prepration" => $prepration,
"category_id" => $category_id,
"category_name" => $category_name
);
array_push($products_arr["data"], $product_item);
}
echo json_encode($products_arr);
} else {
echo json_encode(
array("message" => "No products found.")
);
}
?>
最佳答案
在您的 while 循环中,您可以先通过 category_id
对食谱进行分组,而不是推送整个行数组。然后使用 array_values()
重新索引。
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// extract row
// this will make $row['name'] to
// just $name only
extract($row);
// Check if category_id is already set
if (!array_key_exists($category_id, $products_arr["data"])) {
$products_arr["data"][$category_id] = array(
"category_id" => $category_id,
"category_name" => $category_name,
"recipes" => []
);
}
// Push the recipe details
$products_arr["data"][$category_id]["recipes"][] = array(
"id" => $id,
"recipe_name" => $recipe_name,
"ingredients" => html_entity_decode($ingredients),
"prepration" => $prepration
);
$products_arr["data"] = array_values($products_arr["data"]);
}
echo json_encode($products_arr);
注意:输出与您的预期结果略有不同。因为输出的 data
键具有基于类别的数组,而不是具有 category_id
。如果您使用 category_id
作为 data
关于php - 如何在一个数组PHP中设置子json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47987745/