Sunday, October 9, 2022
HomeWordPress Developmentloop - Forestall duplicating particular column from database desk

loop – Forestall duplicating particular column from database desk


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.

enter image description here

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:

enter image description here
enter image description here

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>';

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments