如何创建、存储和输出使用两个不同 mysql 查询的数组?
我试着举了一个简单的例子。
$select1 = "SELECT country_id, country_name FROM countries ...";
while ($select1) {
...store country results in array...
$select2 = "SELECT city_id, city_name FROM cities where '" . $select1['country_id'] . "'..."); // depends on select1
while ($select2) {
...store city results in array...
}
}
**output something like this:**
country_id = 1
country_name = United States
city_id = 1
city_name = New York
city_id = 2
city_name = Las Vegas
country_id = 2
country_name = Canada
city_id = 3
city_name = Ottawa
最佳答案
我不知道您是否正在检查错误、准备或转义您的查询,但请这样做。
要生成数组,您可以这样做:
$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;
}
要显示您的数组,您可以执行以下操作:
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 />';
}
此外,如果您知道国家 ID 或城市 ID,您可以:
echo 'City Name: ' . $list[$country_id]['country_cities'][$city_id]['city_name'] . '<br />';
关于php - 将两个查询的 MySQL 结果存储在 PHP 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36312038/