sql >> Database teknologi >  >> RDS >> Mysql

Gem MySQL-resultater i PHP-array for to forespørgsler

Jeg ved ikke, om du tjekker for fejl, forbereder eller undslipper dine forespørgsler, men gør det venligst.

For at generere dit array kan du gøre det med dette:

    $list = [];
    $countries = $link->query("SELECT country_id, country_name FROM countries ...");

    while ($country_row /*fetch from $countries*/) {

        $country_id = $country_row['country_id']; 

        $country_info = [
                'country_id' => $country_id,
                'country_name' => $country_row['country_name'],
                'country_cities' => []
         ];

        $cities_stmt = "SELECT city_id, city_name FROM cities where $country_id...";
        $cities = $link->query($cities_stmt);

        while ($city_row /*fetch from $cities*/) {

            $city_id = $city_row['city_id'];

            $country_info['country_cities'][$city_id] = [
                    'city_id' => $city_id,
                    'city_name' => $city_row['city_name']
            ];
        }

        $list[$country_id] = $country_info;
    }

For at vise dit array kan du gøre:

    foreach ( $list as $country_id => $country_info ) {

        echo "Country ID: $country_id<br />";
        echo 'Country Name: ' . $country_info['country_name'] . '<br />';
        echo 'Country Cities:<br />';

        $cities = $country_info['country_cities']; 

        foreach ( $cities as $city_id => $city_info ) {

                echo "   City ID: $city_id<br />";
                echo '   City Name: ' . $city_info['city_name'] . '<br />';
        }

        echo '<br />';
    }

Hvis du kender lande-id'et eller by-id'et, kan du også gøre:

    echo 'City Name: ' . $list[$country_id]['country_cities'][$city_id]['city_name'] . '<br />';


  1. Hvordan kan jeg forbinde ORACLE fra EXCEL med JDBC?

  2. Send formularproblem... Enter-nøgle

  3. Vil du flette 2 tabeller til en SELECT-forespørgsel?

  4. Duplikere en MySQL-tabel, indekser og data