我的数据库看起来像这样......
id,city,name
1,ajo,肚子亩
2,高山,高山村庄
3,apache交界处,失去了荷兰人 4,apache junction,butterfield5,apache junction,benson
6,bisbee,Queen mine
......等等
我正在尝试显示列表...
<section>
<h1>ajo</h1>
<h2>belly acres</h2>
</section>
<section>
<h1>alpine</h1>
<h2>alpine village</h2>
</section>
<section>
<h1>apache junction</h1>
<h2>lost dutchman</h2>
<h2>butterfield</h2>
<h2>benson</h2>
</section>
<section>
<h1>bisbee</h1>
<h2>queen mine</h2>
</section>
我目前使用的代码适用于只有一个名称的城市,但是在Apache Junction的例子中有多个名字,我得到了这个......
<section>
<h1>apache junction</h1>
</section>
<h2>lost dutchman</h2>
<h2>butterfield</h2>
<h2>benson</h2>
<section>
<h1>bisbee</h1>
<h2>queen mine</h2>
</section>
我想在一个部分中显示Apache联结中的所有位置名称。这是我正在使用的代码...
$previousLevel = "";
$city_query = $wpdb->get_results( $wpdb->prepare("SELECT name, city FROM locations") );
foreach ($city_query as $city_list) {
$city = $city_list->city;
$name = $city_list->name;
if ($city != $previousLevel) {
$dump_list .= '<section><h1>' . $city . '</h1>';
$dump_list_end = '</section>';
}
$dump_list .= '<h2><a href="#">' . $name . '</a></h2>';
$dump_list .= $dump_list_end;
$previousLevel = $city;
}
任何帮助都将不胜感激。
答案 0 :(得分:0)
您可以尝试修改此代码吗?
$previousLevel = "";
$city_query = $wpdb->get_results( $wpdb->prepare("SELECT name, city FROM locations") );
foreach ($city_query as $city_list) {
$city = $city_list->city;
$name = $city_list->name;
if ($city != $previousLevel) {
if ($previousLevel != "") {
$dump_list .= '</section>';
}
$dump_list .= '<section><h1>' . $city . '</h1>';
$previousLevel = $city;
}
$dump_list .= '<h2><a href="#">' . $name . '</a></h2>';
}
答案 1 :(得分:0)
修改后的代码,更长,但更容易理解,并且具有正确的数据转义:
$city_query = $wpdb->get_results( $wpdb->prepare("SELECT name, city FROM locations ORDER BY city, name") );
$cities = array();
foreach ($city_query as $city_list) {
if (!isset($cities[$city_list->city])) {
$cities[$city_list->city] = array();
}
$cities[$city_list->city][] = $city_list->name;
}
$dump_list = '';
foreach ($cities as $city => $names) {
$dump_list .= '<section><h1>' . htmlspecialchars($city) . '</h1><h2>';
$dump_list .= implode('</h2><h2>', array_map('htmlspecialchars', $names));
$dump_list .= '</section>';
}