-2

Please see the link below... http://api.androiddeft.com/cities/cities_array.json

I'm trying to nest my results from the DB into the structure below:

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

However what I have tried isn't working, I'm not able to get the results I am looking for:

$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);

This instead results in the following output:

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

]

3
  • you forgot?, okay i'll refresh your memory again, get the json using file_get_contents, then json_decode it (with the true flag), then treat it like any normal array, add as many as you wish. you have to do the coding though. Commented Oct 18, 2018 at 4:29
  • That's not valid JSON. It's also unclear what code you have, and what fixes you attempted so far. Commented Oct 18, 2018 at 4:31
  • I found the answer here... thanks to your answer... stackoverflow.com/questions/34668484/… Commented Oct 19, 2018 at 3:03

1 Answer 1

0

Try:

    $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);
Sign up to request clarification or add additional context in comments.

1 Comment

From review: could you please add some more explanation to your answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.