简体   繁体   中英

Fetching record from two table and convert into json

Hi I'm new in PHP and trying to get the below response using php sql but i'm not be able to find the such desire output

[{"Id":1, "name": "India", "Cities":[{"Id":1, "Name":"Mumbai", "country_id":1}, {"Id":2,"Name":"Delhi","country_id":1},
"id":3,"Name":Banglore","country_id":1}, {"Id":2, "Name":"USA", "Cities":[{"Id":6, "Name":"New York", "country_id":2},.....

I have two tables one is country based and other is city based.

I tried
<?php

    include_once("config.inc.php");

    $sql = "SELECT * FROM country";
    $sqlCity = "SELECT * FROM city";

    $cityQuery = mysqli_query($conn, $sqlCity);
    $sqlQuery = mysqli_query($conn, $sql);

    $mainArray = array();

    if(mysqli_num_rows($cityQuery) > 0 ){
        $cityResponse = array();
        while($resCity = mysqli_fetch_assoc($cityQuery)){
            $cityResponse[] = $resCity;
        }

    if(mysqli_num_rows($sqlQuery) > 0 ){
        $response = array();
        while($res = mysqli_fetch_assoc($sqlQuery)){
            $response[] = $res;
        }
        foreach($cityResponse as $city){
            foreach($response as $country){
                if($city['country_id'] == $country['id']){

                    $mainArray = array("Cities" => $city);
                }
            }
        }
        echo '{"response": '.json_encode($response).', '.json_encode($mainArray).' "success": true}';
    }
    }else{
        echo '{"response": '.json_encode($response).' "success": false}';
    }


?>

currently my response showing

{"response": [{"id":"1","name":"India"},{"id":"2","name":"USA"},{"id":"3","name":"UK"}], {"Cities":{"id":"15","name":"Manchester","country_id":"3"}} "success": true}

use like this

<?php

    include_once("config.inc.php");

    $sql = "SELECT * FROM country";
    $sqlCity = "SELECT * FROM city";

    $cityQuery = mysqli_query($conn, $sqlCity);
    $sqlQuery = mysqli_query($conn, $sql);

    $mainArray = array();

    if(mysqli_num_rows($cityQuery) > 0 ){
        $cityResponse = array();
        while($resCity = mysqli_fetch_assoc($cityQuery)){
            $cityResponse[] = $resCity;
        }

    if(mysqli_num_rows($sqlQuery) > 0 ){
        $response = array();
        while($res = mysqli_fetch_assoc($sqlQuery)){
            $response[] = $res;
        }
        foreach($cityResponse as $city){
            foreach($response as $country){
                if($city['country_id'] == $country['id']){

                    $mainArray = array("Cities" => $city);
                }
            }
        }

        echo json_encode(array('result'=>'true','Cities'=>$mainArray));
    }
    }else{

         echo json_encode(array('result'=>'false','Cities'=>$response));
    }


?>

For detail code explanation check the inline comments

  • Modify the SQL query with related column names
  • The memory you have to take care. By default memory limit in php is 128MB in 5.3
  • Check the code and let me know the result

     <?php $data = array(); //include your database configuration files include_once("config.inc.php"); //execute the join query to fetch the result $sql = "SELECT country.country_id, country.name AS country_name,". " city.city_id, city.name AS city_name FROM country ". " JOIN city ON city.country_id=country.country_id ". " ORDER BY country.country_id "; //execute query $sqlQuery = mysqli_query($conn, $sql) or die('error exists on select query'); //check the number of rows count if(mysqli_num_rows($sqlQuery) > 0 ){ //country id temprory array $country_id = array(); //loop each result while($result = mysqli_fetch_assoc($sqlQuery)){ //check the country id is already exist the only push the city entries if(!in_array($result['country_id'],$country_id)) { //if the city is for new country then add it to the main container if(isset($entry) && !empty($entry)) { array_push($data, $entry); } //create entry array $entry = array(); $entry['Id'] = $result['country_id']; $entry['name'] = $result['country_name']; $entry['Cities'] = array(); //create cities array $city = array(); $city['Id'] = $result['city_id']; $city['name'] = $result['city_name']; $city['country_id'] = $result['country_id']; //append city entry array_push($entry['Cities'], $city); $country_id[] = $result['country_id']; } else { //create and append city entry only $city = array(); $city['Id'] = $result['city_id']; $city['name'] = $result['city_name']; $city['country_id'] = $result['country_id']; array_push($entry['Cities'], $city); } } } //display and check the expected results echo json_encode($data); 

You can use try this. It actually works for me and it's cool. You can extend to 3 or more tables by editing the code.

try {

    $results = array();

    $query = "SELECT * FROM country";
    $values = array();

    $stmt = $datab->prepare($query);
    $stmt->execute($values);

    while($country = $stmt->fetch(PDO::FETCH_ASSOC)){

        $cities = null;

        $query2 = "SELECT * FROM city WHERE country_id = ?" ;
        $values2 = array($country['id']);

        $stmt2 = $datab->prepare($query2);
        $stmt2->execute($values2);
        $cities = $stmt2->fetchAll();

        if($cities){
            $country['cities'] = $cities;
        } else {
            $country['cities'] = '';
        }

        array_push($results, $country);  
    }

    echo json_encode(array("Countries" => $results));

} catch (PDOException $e) {
    throw new Exception($e->getMessage());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM