I’ve SQL desk of cities and counties. I have to loop over them and create dropdown with labels. Cities needs to be an <possibility>
components and counties wrapper <optgroup>
s.
perform my_custom_shortcode() {
world $wpdb;
$outcomes = $wpdb->get_results( "SELECT metropolis, county FROM slovak_cities" );
$choose="<choose identify="city_field">";
foreach ( $outcomes as $end result ) {
$metropolis = $result->metropolis;
$county = $result->county;
$choose .= '<optgroup label="' . $county . '">';
$choose .= '<possibility worth="' . $metropolis . '">' . $metropolis . '</possibility>';
$choose .= '</optgroup>';
}
$choose .= '</choose>';
return $choose;
}
add_shortcode( 'my_shortcode', 'my_custom_shortcode' );
Counties are such teams of cities and needs to be displayed just one time with out duplicating in each iteration.
I get outcomes like this:
Counties are duplicated and created wrapper of each metropolis each iteration.
It needs to be one county <optgroup>
wrapper for all cities related to it.
So I attempted to edit my code, however outcomes are utterly fallacious:
world $wpdb;
$outcomes = $wpdb->get_results( "SELECT DISTINCT metropolis, county FROM slovakia_cities" );
$choose="<choose id="city_field" identify="city_field" data-required="sure" data-type="choose">";
$no_duplicates = array();
foreach ( $outcomes as $end result ) {
$metropolis = $result->metropolis;
$county = $result->county;
if ( ! in_array( $county, $no_duplicates ) ) {
$choose .= '<optgroup label="' . $county . '">';
$choose .= '<possibility worth="' . $metropolis . '">' . $metropolis . '</possibility>';
$choose .= '</optgroup>';
array_push( $no_duplicates, $county );
}
}
$choose .= '</choose>';