如何从联结点 table 获取结果并使用 PHP 将它们作为数组插入到 JSON 对象中?

How can I fetch results from a junction table and insert them as an array into a JSON object using PHP?

我在 mysql 数据库中有带类别的文章。我想打印出所有文章及其相应类别的 JSON in PHP 以使用我的 Vue-App 获取。

我正在处理以下 tables:文章、类别和 Article_has_Category(连接点 table,多对多):

Articles

"ID" | "Title"
------------
1    | First
2    | Second


Categories

"ID" | "Category"
------------
1    | Lifestyle
2    | Webtech


Article_has_Categories

"ID" | "Article_ID" | "Category_ID"
--------------------------------------
1    |     1        |     1    
2    |     1        |     2    

以下 PHP- 代码选择并打印所有文章供我的前端获取:


$stmt = $pdo->prepare("SELECT * FROM Articles;");

$stmt->bindParam(':param');

if ($stmt->execute()) {

  $array = $stmt->fetchAll();

  $jsonArray = json_encode($array);

  print_r($jsonArray);

}

Printed JSON-Output:

[
{"ID":"1","Title":"First"},
{"ID":"2","Title":"Second"}
]

是否可以将所有类别作为数组插入到 JSON- 输出中?

Desired JSON-Output:

[
{"ID":"1","Title":"First", "Categories": "[Lifestyle, Webtech]" },
{"ID":"2","Title":"Second", "Categories": "[]"}
]

目前我首先使用“SELECT * FROM Articles;”在我的前端构建所需的对象获取所有文章,然后在单独的调用中,使用以下语句按文章 ID 获取相应的类别:


SELECT c.Category
FROM article_has_category ac 
INNER JOIN Categories c ON c.ID = ac.Category_ID
WHERE ac.Article_ID = :id;

是否有任何解决方案可以结合这两个语句并直接在我的 PHP 文件中构建所需的对象?

好吧,我通过在 PHP 中组装自己的 JSON 解决了这个问题,而不是使用 json_encode()。

我的代码不是很漂亮,但我对它做了一些评论,以便您理解:

<?php

$stmt = $pdo->prepare("

SELECT * FROM Articles;

");

$stmt_categories = $pdo->prepare("

SELECT c.Category
FROM article_has_category ac
INNER JOIN Categories c ON c.ID = ac.Category_ID
WHERE ac.Article_ID = :id;

");

if ($stmt->execute()) {

  $result = $stmt -> fetchAll();

  // count items in result, in order to determine later which is the last one
  $numItems = count($result);
  $i = 0;

  // prepare the json-array to print out in the php file
  $printArray = '[';

  // for each article, run the second sql-statement using the article-ID
  foreach( $result as $row ) {

    $stmt_categories->bindParam(':id', $row['ID']);

    // executing the second statement
    if ($stmt_categories->execute()) {

      $result_category = $stmt_categories -> fetchAll();

      // save the fetched categories into a new array, using the function makeArray()
      $categories = makeArray($result_category);

      // build the json object by hand, no more need for json_encode()
      $element = '{';

        $element .= ' "ID": ';
        $element .= '"' . $row['ID'] . '",';

        $element .= $categories;

        $element .= ' "Title": ';
        $element .= '"' . $row['Title'] . '"';

        $element .= '}';

        if(++$i === $numItems) {

          // if it's the last item, do nothing

        } else {

          // if not, add a comma

          $element .= ',';

        }

        // add the built element to the printArray
        $printArray .= $element;


      }
    }

    $printArray .= ']';

    // finally print the array
    print_r($printArray);


  }

  function makeArray($categoryArray){

    $category_element .= ' "Category": ';
    $category_element .= "[";

    $numCategories = count($categoryArray);
    $n = 0;

    foreach( $categoryArray as $row ) {


      $category_element .= '"' . $row['Category'] . '"';

      if(++$n === $numCategories) {

        // if it's the last item, do nothing

      } else {

        // if not, add a comma

        $category_element .= ',';

      }

    }

    $category_element .= "],";


    return $category_element;

  }