如何选择数据到数组字段?

时间:2017-06-07 02:10:30

标签: php mysql json

表A:

idA: 1, name: John;

表B:

idB: 1, product: milk, idA: 1;
idB: 2, product: egg, idA: 1;

我希望最终的JSON结果如下:

[
    {
        "idA": 1, 
        "name": "John", 
        "TableB": [
            {
                "idB": 1, 
                "product": "milk", 
                "idA": 1
            },
            {
                "idB": 2, 
                "product": "egg", 
                "idA": 1
            }
        ]
    }
]

我正在使用PHP和mySQL。 查询应该如何? 非常感谢! 我很抱歉,因为我的英语不太好。

3 个答案:

答案 0 :(得分:0)

使用Mysqli或pdo。检查下面的代码。我没有测试,但它应该工作。

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM TableA ORDER BY idA";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

  $rows = array();
  while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;

    $sqlSub = "SELECT * FROM TableB WHERE idA = '{$row['idA']}' ORDER BY idB";  
    $resultSub = mysqli_query($conn, $resultSub);

    if (mysqli_num_rows($resultSub) > 0) {
        while ($rowSub = mysqli_fetch_array($resultSub)) {

            $rows[]['TableB'][] = $rowSub;
        }
    }

  }

  echo json_encode($rows);
} else {
  echo "no results found";
}

答案 1 :(得分:0)

此查询将返回给您一行。我没有测试它,但它应该工作得很好。

select tA.idA,name, group_concat(idB) as cIdB,
 group_concat(product) as cProduct ,
 group_concat(tB.idA) as cIdA 
from Table A tA
left join Table B tB on tA.idA = tB.idA group by tB.idA 

它应该返回一个如下所示的数组:

idA          1
name         Jhon
cIdB         1,2
cProduct     milk,egg
cIdA         1,1

希望它有所帮助。

答案 2 :(得分:0)

使用内部联接从SQL获取行:

select TableA.*, TableB.* from TableA, TableB where TableA.idA = TableB.idA

以PHP格式化数据:

$formattedResults = array(
"idA" => $result.idA, "name" =>  $result.name, "TableB" => array();
);
foreach ($results as $result) {
    $formattedResults["TableB"][] = array("idB"=> result.idB, "product"=> 
    result.product, "idA"=> result.idA;);
}

$json = json_encode($formattedResults);