从PHP关联数组生成分组的HTML选择列表

时间:2015-07-11 16:48:19

标签: php arrays recursion nested kohana

我正在尝试在Kohana中生成schema.org支持的微数据模式的嵌套分组选择列表(optgroup / option)。这是我的数组,__('要翻译的东西'):

public function get_supported_schemas()
{
    return array(

        __('EducationalOrganization') => array(

            'CollegeOrUniversity'   => __('CollegeOrUniversity'),
            'ElementarySchool'      => __('ElementarySchool'),
            'HighSchool'            => __('HighSchool'),
            'MiddleSchool'          => __('MiddleSchool'),
            'Preschool'             => __('Preschool'),
            'School'                => __('School'),

        ),

        __('LocalBusiness') => array(

            'AnimalShelter' => __('AnimalShelter'),

            __('AutomotiveBusiness') => array(

                'AutoBodyShop'      => __('AutoBodyShop'),
                'AutoDealer'        => __('AutoDealer'),
                'AutoPartsStore'    => __('AutoPartsStore'),
                'AutoRental'        => __('AutoRental'),
                'AutoRepair'        => __('AutoRepair'),
                'AutoWash'          => __('AutoWash'),
                'GasStation'        => __('GasStation'),
                'MotorcycleDealer'  => __('MotorcycleDealer'),
                'MotorcycleRepair'  => __('MotorcycleRepair'),

            ),

            'DryCleaningOrLaundry' => __('DryCleaningOrLaundry'),

            __('EmergencyService') => array(

                'FireStation'   => __('FireStation'),
                'Hospital'      => __('Hospital'),
                'PoliceStation' => __('PoliceStation'),

            ),

            'EmploymentAgency' => __('EmploymentAgency'),

            __('EntertainmentBusiness') => array(

                //'AdultEntertainment'  => __('AdultEntertainment'), // not supported by Yandex
                'AmusementPark'         => __('AmusementPark'),
                'ArtGallery'            => __('ArtGallery'),
                'Casino'                => __('Casino'),
                //'ComedyClub'          => __('ComedyClub'), // not supported by Yandex
                'NightClub'             => __('NightClub'),

            ),

            __('FinancialService') => array(                    

                'AccountingService' => __('AccountingService'),
                'AutomatedTeller'   => __('AutomatedTeller'),
                'BankOrCreditUnion' => __('BankOrCreditUnion'),
                'InsuranceAgency'   => __('InsuranceAgency'),

            ),

            __('FoodEstablishment') => array(                   

                'Bakery'                => __('Bakery'),
                'BarOrPub'              => __('BarOrPub'),
                'Brewery'               => __('Brewery'),
                'CafeOrCoffeeShop'      => __('CafeOrCoffeeShop'),
                'FastFoodRestaurant'    => __('FastFoodRestaurant'),
                //'IceCreamShop'        => __('IceCreamShop'), // not supported by Yandex
                'Restaurant'            => __('Restaurant'),
                'Winery'                => __('Winery'),

            ),

            __('GovernmentOffice') => array(                    

                'PostOffice' => __('PostOffice'),                   

            ),

            __('HealthAndBeautyBusiness') => array(                 

                'BeautySalon'   => __('BeautySalon'),                   
                'DaySpa'        => __('DaySpa'),                    
                'HairSalon'     => __('HairSalon'),                 
                'HealthClub'    => __('HealthClub'),                    
                'NailSalon'     => __('NailSalon'),                 
                'TattooParlor'  => __('TattooParlor'),                  

            ),

            __('HomeAndConstructionBusiness') => array(                 

                'Electrician'       => __('Electrician'),                   
                'GeneralContractor' => __('GeneralContractor'),                 
                //'HVACBusiness'    => __('HVACBusiness'), // not supported by Yandex
                //'HousePainter'    => __('HousePainter'), // not supported by Yandex
                //'Locksmith'       => __('Locksmith'), // not supported by Yandex
                'MovingCompany'     => __('MovingCompany'),                 
                'Plumber'           => __('Plumber'),                   
                'RoofingContractor' => __('RoofingContractor'),                 

            ),

            'InternetCafe'  => __('InternetCafe'),              
            'Library'       => __('Library'),

            __('LodgingBusiness') => array(                 

                //'BedAndBreakfast' => __('BedAndBreakfast'), // not supported by Yandex
                'Hostel'    => __('Hostel'),                    
                'Hotel'     => __('Hotel'),                 
                'Motel'     => __('Motel'),                 

            ),

            __('MedicalOrganization') => array(

                'Dentist'           => __('Dentist'),                   
                'Hospital'          => __('Hospital'),                  
                'MedicalClinic'     => __('MedicalClinic'),                 
                'Optician'          => __('Optician'),                  
                'Pharmacy'          => __('Pharmacy'),                  
                'Physician'         => __('Physician'),                 
                'VeterinaryCare'    => __('VeterinaryCare'),                    

            ),

            __('ProfessionalService') => array(

                'AccountingService' => __('AccountingService'),                 
                'Attorney'          => __('Attorney'),                  
                'Dentist'           => __('Dentist'),                   
                'Electrician'       => __('Electrician'),                   
                'GeneralContractor' => __('GeneralContractor'),                 
                //'HousePainter'    => __('HousePainter'), // not supported by Yandex
                //'Locksmith'       => __('Locksmith'), // not supported by Yandex
                'Notary'            => __('Notary'),                    
                'Plumber'           => __('Plumber'),                   
                'RoofingContractor' => __('RoofingContractor'),                 

            ),

            'RadioStation'      => __('RadioStation'),              
            'RealEstateAgent'   => __('RealEstateAgent'),               
            'RecyclingCenter'   => __('RecyclingCenter'),               
            'SelfStorage'       => __('SelfStorage'),               
            'ShoppingCenter'    => __('ShoppingCenter'),

            __('SportsActivityLocation') => array(                  

                'BowlingAlley'          => __('BowlingAlley'),
                'ExerciseGym'           => __('ExerciseGym'),
                //'GolfCourse'          => __('GolfCourse'), // not supported by Yandex
                'HealthClub'            => __('HealthClub'),
                'PublicSwimmingPool'    => __('PublicSwimmingPool'),
                'SkiResort'             => __('SkiResort'),
                'SportsClub'            => __('SportsClub'),
                'StadiumOrArena'        => __('StadiumOrArena'),
                'TennisComplex'         => __('TennisComplex'),                             

            ),

            __('Store') => array(                   

                'AutoPartsStore'        => __('AutoPartsStore'),
                'BikeStore'             => __('BikeStore'),
                'BookStore'             => __('BookStore'),
                'ClothingStore'         => __('ClothingStore'),
                'ComputerStore'         => __('ComputerStore'),
                //'ConvenienceStore'    => __('ConvenienceStore'), // not supported by Yandex
                'DepartmentStore'       => __('DepartmentStore'),
                'ElectronicsStore'      => __('ElectronicsStore'),
                'Florist'               => __('Florist'),
                'FurnitureStore'        => __('FurnitureStore'),
                'GardenStore'           => __('GardenStore'),
                'GroceryStore'          => __('GroceryStore'),
                //'HardwareStore'       => __('HardwareStore'), // not supported by Yandex
                //'HobbyShop'           => __('HobbyShop'), // not supported by Yandex
                'HomeGoodsStore'        => __('HomeGoodsStore'),
                'JewelryStore'          => __('JewelryStore'),
                'LiquorStore'           => __('LiquorStore'),
                'MensClothingStore'     => __('MensClothingStore'),
                'MobilePhoneStore'      => __('MobilePhoneStore'),
                'MovieRentalStore'      => __('MovieRentalStore'),
                'MusicStore'            => __('MusicStore'),
                'OfficeEquipmentStore'  => __('OfficeEquipmentStore'),
                //'OutletStore'         => __('OutletStore'), // not supported by Yandex
                'PawnShop'              => __('PawnShop'),
                'PetStore'              => __('PetStore'),
                'ShoeStore'             => __('ShoeStore'),
                'SportingGoodsStore'    => __('SportingGoodsStore'),
                'TireShop'              => __('TireShop'),
                'ToyStore'              => __('ToyStore'),
                'WholesaleStore'        => __('WholesaleStore'),                

            ),

            'TelevisionStation'             => __('TelevisionStation'),
            //'TouristInformationCenter'    => __('TouristInformationCenter'), // not supported by Yandex
            'TravelAgency'                  => __('TravelAgency'),          

        ),

        __('PerformingGroup') => array(                 

            //'DanceGroup'          => __('DanceGroup'), // not supported by Yandex
            'MusicGroup'            => __('MusicGroup'),
            //'TheaterGroup'            => __('TheaterGroup'), // not supported by Yandex

        ),

    );
}

Kohana表单助手方法Form :: select($ name,array $ options = NULL,$ selected = NULL,array $ attributes = NULL)仅适用于具有一个级别深度的关联数组,因此我们得到了这样的结果:< / p>

<select>
    <option value="0">—&nbsp;Choose a scheme type</option>
    <optgroup label="EducationalOrganization">
        <option value="CollegeOrUniversity">CollegeOrUniversity</option>
        <option value="ElementarySchool">ElementarySchool</option>
        <option value="HighSchool">HighSchool</option>
        <option value="MiddleSchool">MiddleSchool</option>
        <option value="Preschool">Preschool</option>
        <option value="School">School</option>
    </optgroup>
    <optgroup label="LocalBusiness">
        <option value="AnimalShelter">AnimalShelter</option>
        <option value="AutomotiveBusiness">Array</option>
        <option value="DryCleaningOrLaundry">DryCleaningOrLaundry</option>
        <option value="EmergencyService">Array</option>
        <option value="EmploymentAgency">EmploymentAgency</option>
        <option value="EntertainmentBusiness">Array</option>
        <option value="FinancialService">Array</option>
        <option value="FoodEstablishment">Array</option>
        <option value="GovernmentOffice">Array</option>
        <option value="HealthAndBeautyBusiness">Array</option>
        <option value="HomeAndConstructionBusiness">Array</option>
        <option value="InternetCafe">InternetCafe</option>
        <option value="Library">Library</option>
        <option value="LodgingBusiness">Array</option>
        <option value="MedicalOrganization">Array</option>
        <option value="ProfessionalService">Array</option>
        <option value="RadioStation">RadioStation</option>
        <option value="RealEstateAgent">RealEstateAgent</option>
        <option value="RecyclingCenter">RecyclingCenter</option>
        <option value="SelfStorage">SelfStorage</option>
        <option value="ShoppingCenter">ShoppingCenter</option>
        <option value="SportsActivityLocation">Array</option>
        <option value="Store">Array</option>
        <option value="TelevisionStation">TelevisionStation</option>
        <option value="TravelAgency">TravelAgency</option>
    </optgroup>
    <optgroup label="PerformingGroup">
        <option value="MusicGroup">MusicGroup</option>
    </optgroup>
</select>

更深的级别打印为数组。所以我们只有一个级别列表深度。 Kohana表格::选择就在这里:

/**
 * Creates a select form input.
 *
 *     echo Form::select('country', $countries, $country);
 *
 * [!!] Support for multiple selected options was added in v3.0.7.
 *
 * @param   string  $name       input name
 * @param   array   $options    available options
 * @param   mixed   $selected   selected option string, or an array of selected options
 * @param   array   $attributes html attributes
 * @return  string
 * @uses    HTML::attributes
 */
public static function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL)
{
    // Set the input name
    $attributes['name'] = $name;

    if (is_array($selected))
    {
        // This is a multi-select, god save us!
        $attributes[] = 'multiple';
    }

    if ( ! is_array($selected))
    {
        if ($selected === NULL)
        {
            // Use an empty array
            $selected = array();
        }
        else
        {
            // Convert the selected options to an array
            $selected = array( (string) $selected);
        }
    }

    if (empty($options))
    {
        // There are no options
        $options = '';
    }
    else
    {
        foreach ($options as $value => $name)
        {
            if (is_array($name))
            {
                // Create a new optgroup
                $group = array('label' => $value);

                // Create a new list of options
                $_options = array();

                foreach ($name as $_value => $_name)
                {
                    // Force value to be string
                    $_value = (string) $_value;

                    // Create a new attribute set for this option
                    $option = array('value' => $_value);

                    if (in_array($_value, $selected))
                    {
                        // This option is selected
                        $option[] = 'selected';
                    }

                    // Change the option to the HTML string
                    $_options[] = '<option'.HTML::attributes($option).'>'.HTML::chars($_name, FALSE).'</option>';
                }

                // Compile the options into a string
                $_options = "\n".implode("\n", $_options)."\n";

                $options[$value] = '<optgroup'.HTML::attributes($group).'>'.$_options.'</optgroup>';
            }
            else
            {
                // Force value to be string
                $value = (string) $value;

                // Create a new attribute set for this option
                $option = array('value' => $value);

                if (in_array($value, $selected))
                {
                    // This option is selected
                    $option[] = 'selected';
                }

                // Change the option to the HTML string
                $options[$value] = '<option'.HTML::attributes($option).'>'.HTML::chars($name, FALSE).'</option>';
            }
        }

        // Compile the options into a single string
        $options = "\n".implode("\n", $options)."\n";
    }

    return '<select'.HTML::attributes($attributes).'>'.$options.'</select>';
}

感谢您的帮助!

0 个答案:

没有答案