【问题标题】:concat two mysql tables and convert it to json with php连接两个mysql表并使用php将其转换为json
【发布时间】:2022-01-05 00:26:49
【问题描述】:

我在一个项目中使用带有 PDO 的 PHP 我的数据库中有以下两个表。

Category

CategoryID  | Name          | CategoryCode  
1           | Fixed         | FA    
2           | Consumable    | CA    
3           | Intangible    | IA

Type

TypeID | CategoryID | Name                              | TypeCode  
1      | 1          | Furniture                         | FU    
2      | 1          | Computers & Computer Peripherals  | CP    
3      | 1          | Electrical Appliances             | EA    
4      | 1          | Machinery                         | MA    
5      | 2          | Computer Peripherals              | PE    
6      | 3          | Software                          | SW        

我需要从选择操作中获得如下输出。我用 group concat 然后 fecthAll() 尝试过,但它没有给我正确 JSON 的结果

Output

[
  {
    "CategoryID": 1,
    "Name": "Fixed",
    "CategoryCode": "FA",
    "Types": [
      {
        "TypeID": 1,
        "Name": "Furniture",
        "TypeCode": "FU"
      },
      {
        "TypeID": 2,
        "Name": "Computers & Computer Peripherals",
        "TypeCode": "CP"
      },
      {
        "TypeID": 3,
        "Name": "Electrical Appliances",
        "TypeCode": "EA"
      }
    ]
  },
  {
    "CategoryID": 2,
    "Name": "Consumable",
    "CategoryCode": "CA",
    "Types": [
      {
        "TypeID": 5,
        "Name": "Computer Peripherals",
        "TypeCode": "PE"
      }
    ]
  }
]

【问题讨论】:

  • 请发布您尝试的查询。
  • 请运行SELECT version();查看具体的MySQL版本。

标签: php mysql json pdo


【解决方案1】:

想办法得到我想要的输出

protected function getCategories(){
        $dbConnection = $this->connect();
        $catSql = 'SELECT * FROM `category`';
        $stmt = $dbConnection->prepare($catSql);
        $stmt->execute();
        $result = $stmt->fetchAll();
        $output = array();
        foreach ($result as $row) {
            $line = array("CategoryID" => $row['CategoryID'], "CategoryName" => $row['Name'], "CategoryCode" => $row['CategoryCode']);
            $typeSQL =  'SELECT
                    TypeID,
                    Name,
                    TypeCode
                FROM type
                WHERE
                    CategoryID = ' . $row['CategoryID'];
            $stmt2 = $dbConnection->prepare($typeSQL);
            $stmt2->execute();
            $types = $stmt2->fetchAll();
            $typeArray = array();
            foreach ($types as $type) {
                $typeLine = array("TypeID" => $type['TypeID'], "TypeName" => $type['Name'], "TypeCode" => $type['TypeCode']);
                array_push($typeArray, $typeLine);
            }
            $line['Types'] = $typeArray;
            array_push($output, $line);
        }
        return json_encode($output);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2018-05-30
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    相关资源
    最近更新 更多