如何在 PHP 中将子 JSON 数组设置为一个数组

3

我是一个新手,正在学习php,我试图从以下响应中获取数据,但我想将这些数据设置在子数组中。如何做到这一点?我有两个不同的表格categoryProduct。如何按类别显示多个产品。

非常感谢!

{
    "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()
        // https://dev59.com/enE85IYBdhLWcg3wdDIM
        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.")
        );
    }
?>
3个回答

2
在你的 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。如果在data内使用category_id作为键,则会防止多个类别被覆盖。


谢谢您的指导 :) - Chitra Nandpal
我应该怎么做,才能避免重复使用我的类别 ID? - Chitra Nandpal

1
我建议您在获取类别及其相关产品记录时使用JOIN。这将需要一个查询和一个循环来生成所需的数组。以下是示例查询,您可以使用它。它将获取每个产品记录的类别名称,并且不显示其中没有产品的类别。
SELECT * FROM categories AS c LEFT JOIN offers AS p ON c.category_id=p.category_id WHERE p.offer_id IS NOT NULL

注意:在搜索查询中不要使用星号(*),请使用表字段名称。
<?php

// initialize empty category array
$categoryArr = [];
// $row has product info with category id and name in it.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){

    /* First key of categoryArr variable is category id. It will automatically create array key for each category.
    *   If an array key already exists, it will add prodcts in it.
    */
    $categoryArr[$row['category_id']]['category_id'] = $row['category_id'];
    $categoryArr[$row['category_id']]['category_name'] = $row['category_name'];
    $categoryArr[$row['category_id']]['products'][] = $row;
}
/* Once loop done with its work. Need to reset array keys with the help of below function. */
$result = array_values($categoryArr);

echo json_encode($result); ?>

我还没有测试过它,只是为了让你有个想法。希望你能改进它。


它实际上起作用了!非常感谢 :) - Chitra Nandpal

0

// 希望它有用..

$returnArr = array('category_id' => $category_id,'category_name' => $category_name,$products_arr["data"]); // in last "$products_arr["data"]" set your dynamic code ..

$arr = array('recipes' => $returnArr); 

echo json_encode($arr['recipes']); // print json ..

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接