如何使用PHP将MySQL结果嵌套到JSON数组中?

时间:2018-10-18 04:24:27

标签: php mysql json

请参见下面的链接... http://api.androiddeft.com/cities/cities_array.json

我正在尝试将数据库中的结果嵌套到以下结构中:

[
    {
        region:"1",
        province:[{
           "Ilocos Norte",
           "Ilocos Sur"  
         }]
    },
    {
        region:"2",
        province:[{
           "Isabela",
           "Cagayan"  
         }]
    }
]

但是我尝试的方法不起作用,但无法获得所需的结果:

$rows = array();
$rs = array();
$result = mysqli_query($connect, "SELECT regDesc, regCode FROM refregion ORDER BY regCode ASC");

while($row=mysqli_fetch_array($result)){
    $result2 = mysqli_query($connect, "SELECT provDesc FROM refprovince WHERE regCode = '".$row["regCode"]."' ORDER BY provCode ASC");      

    while($rs=mysqli_fetch_array($result2))

    $rows[] = array(
        'region' => $row["regDesc"],
        'province'=>$rs["provDesc"]
        );
    }           

echo json_encode($rows);

这将导致以下输出:

[
  {
    region: "REGION I",
    province: "ILOCOS NORTE"
  },
  {
    region: "REGION I",
    province: "ILOCOS SUR"
  },
  {
    region: "REGION II",
    province: "CAGAYAN"
  },
  {
    region: "REGION II",
    province: "ISABELA"
  }

]

1 个答案:

答案 0 :(得分:0)

尝试:

    $rows = array();
    $rs = array();
    $result = mysqli_query($connect, "SELECT regDesc, regCode FROM refregion ORDER BY regCode ASC");
    while($row=mysqli_fetch_array($result)){
        $region = $row['regDesc'];
        $result2 = mysqli_query($connect, "SELECT provDesc FROM refprovince WHERE regCode = '".$row["regCode"]."' ORDER BY provCode ASC");      

        while($rs=mysqli_fetch_array($result2)){
            array_push($province,$rs['provDesc'];
        }           

        $tempArray = array(
            'region' => $region,
            'province' => $province
        )

        array_push($rows,$tempArray);
    }

    echo json_encode($rows);