尝试合并两个数组不起作用

时间:2019-09-27 12:11:39

标签: php arrays

我正在尝试将两个选择框组合为一个。这是代码:

//Selectbox 1
<?php $aCities = City::newInstance()->listAll(); ?>
<?php if(count($aCities) > 0 ) { ?>
    <select id="dropdowncities">
        <option value=""><?php _e('Select your location...')?></option>
        <?php foreach($aCities as $city) { ?>
            <option value="<?php echo $city['s_name'] ; ?>"><?php echo $city['s_name'] ; ?>
            </option>
        <?php } ?>
    </select>
<?php } ?>


//Selectbox 2
<?php $aRegions = Region::newInstance()->listAll(); ?>
<?php if(count($aRegions) > 0 ) { ?>
    <select id="dropdownregions">
        <option value=""><?php _e('Select your Region...')?></option>
        <?php foreach($aRegions as $region) { ?>
            <option value="<?php echo $region['s_name'] ; ?>"></option>
        <?php } ?>
    </select>
<?php } ?>

现在,两个选择框都可以正常工作,并且我在其中获得了正确的结果/值。但是,当我尝试将它们组合成一个单独的选择框时,如下面的代码所示,我什么都没有得到:

//Combine two select boxes
<?php $aRegions = Region::newInstance()->listAll(); ?>
<?php $aCities = City::newInstance()->listAll(); ?>
<?php $cityandregion = array_combine($aRegions, $aCities); ?>
<?php if(count($aCities) > 0 ) { ?>
    <select id="dropdowncitiesregions">
        <option value=""><?php _e('Select your city and region...')?></option>
        <?php foreach($cityandregion as $city=>$region) { ?>
            <option value="<?php echo $city['s_name'] ; ?><?php echo $region['s_name'] ; ?>"><?php echo $cityandregion['s_name'] ; ?></option>
        <?php } ?>
    </select>
<?php } ?>

我做错了什么?

更新:我在调试文件中收到此消息->“ PHP警告:array_combine():两个参数应具有相等数量的元素”

1 个答案:

答案 0 :(得分:0)

<?php
    $cityandregion = array(
        "cities" => Region::newInstance()->listAll(),
        "regions" => City::newInstance()->listAll()
    ); 
    if(count($cityandregion["cities"]) > 0 && count($cityandregion["regions"])) {
        // Regions..
        $html = "<select id=\"dropdownregions\">";
        $html .= "<option value=\"\">('Select your region...')</option>";
        foreach($cityandregion["regions"] as $k => $region) {
            $html .= "<option value=\"" . $region['s_name'] . "\">" . $region['s_name'] . "</option>";
        }
        $html .= "</select></ br>";

        // Cities..
        $html = "<select id=\"dropdowncities\">";
        $html .= "<option value=\"\">('Select your city...')</option>";
        foreach($cityandregion["cities"] as $k => $city) {
            $html .= "<option value=\"" . $city['s_name'] . "\">" . $city['s_name'] . "</option>";
        }
        $html .= "</select></ br>";

        echo $html;
    }
?>