将值添加到PHP数组中的特定键位置

时间:2014-07-30 16:50:45

标签: javascript php arrays string web

我正在使用一个库,该库除了其他参数之外还包含一个名称数组,并创建一个<select>组合框,其中包含以该数组中的名称命名的<option>元素。它还为value节点的<option>属性分配了获取名称的索引的值。因此,例如,如果数组的索引0包含“foo”,那么它将创建如下标记:<option value="0">foo</option>。作为参考,这是该库的代码:

function generateSelect(objDimensionAssoc, obj, select_name, label_name, function_name, state, DivAlignement)
{
    //Valid object before
    sChaine = "";
    if(  (obj != null) && (obj != undefined) && (obj != "") && (parseInt(countObject(obj)) > 0) ){
        if( state == 'show' ){

            sChaine +="<label for='"+select_name+"' ><span>"+label_name+"</span></label>\n";
            sChaine +="<div class='"+DivAlignement+"'>\n";
            if(function_name != "")
                sChaine +="<select name='"+select_name+"' id='"+select_name+"' onchange='"+function_name+"' >\n";
            else
                sChaine +="<select name='"+select_name+"' id='"+select_name+"'>\n";

            //lang = variable reconnu dans tout les pages

            for (var x=0; x < obj.length; x++){
                //One or two domentionnal array
                if(obj[x] != null){
                    if(objDimensionAssoc == "1"){
                        if(chaineUrl){
                            sChaine += compare_and_create( x, obj[x], chaineUrl[select_name], select_name);
                        } else {
                            sChaine += compare_and_create( x, obj[x], "", select_name);
                        }
                    } else { 
                        if(chaineUrl){  
                            sChaine += compare_and_create( x, obj[x][lang], chaineUrl[select_name], select_name);
                        } else {
                            sChaine += compare_and_create( x, obj[x][lang], "", select_name);
                        }
                    }
                }
            }

            sChaine +="</select>\n";
            sChaine +="</div>\n";

        }
        return(sChaine);
    } else {
        //empty array
        if( state == 'show' ){
            sChaine +="<label for='"+select_name+"' ><span>"+label_name+"</span></label>\n";
            sChaine +="<div class='"+DivAlignement+"'>\n";
            sChaine +="<select name='"+select_name+"' id='"+select_name+"' disabled='true' >\n";
            sChaine +="<option value='0'>&nbsp;</option>\n";
            sChaine +="</select>\n";
            sChaine +="</div>\n";
        }
        return(sChaine);
    }
}

function compare_and_create( key, innerText, string_compare,select_name)
{
    if(key == string_compare){
        return ("<option value='"+key+"' selected='selected'>"+innerText+"</option>\n");
    } else {
        return ("<option value='"+key+"'>"+innerText+"</option>\n");
    }
}

这就是我所说的:

myDiv = document.getElementById('tmp_stationDiv');
var stationsList = new Array();
stationsList = JSON.parse(<?php getStationList($regions); ?>);
myDiv.innerHTML = generateSelect("1",stationsList,
                            "slt_idStations",message["txt_choose_station"][lang],
                            '','show','blockDiv');

这是函数getStationList()

的代码
function getStationList($regions)
{
    $slt_nomStations = (isset($_GET["slt_nomStations"]) ? $_GET["slt_nomStations"] : 0);;
    $db = ConnectionFactory::getFactory()->getConnection();
    $stmt = $db->prepare("SELECT DISTINCT S.station_id, S.name, SA.sub_area_name FROM dev.Station AS S INNER JOIN dbo.SubArea AS SA ON S.sub_area_id = SA.sub_area_id INNER JOIN data.MonthlyNormalData as MND ON MND.station_id = S.station_id WHERE sub_area_name = '$regions[$slt_nomStations]' AND value IS NOT NULL ORDER BY S.name ASC");
    $stmt->execute();

    $stations = array();
    $lastStationName = "";
    while ($row = $stmt->fetch())
    {
        if ($lastStationName != $row['name'])
        {
            array_push($stations, $row['name']);
            $lastStationName = $row['name'];
        }
    }

    $newJSArray = json_encode($stations);
    echo json_encode($newJSArray);
}

现在这完全没问题。 getStationList()的输出例如是"[\"LA GRANDE RIVIERE A\"]",然后我使用JSON.parse()将其转换为javascript数组。

不幸的是,与value节点关联的<option>将为0,1,2,...,n,其中n是站点数量 - 1.我想关联具有站ID的站的名称(我从数据库中恢复),因此与value节点关联的<option>将是那些ID。为此,我想我需要在相应ID的索引处推送站的名称。我尝试对getStationList()进行以下修改:

function getStationList($regions)
{
    $slt_nomStations = (isset($_GET["slt_nomStations"]) ? $_GET["slt_nomStations"] : 0);;
    $db = ConnectionFactory::getFactory()->getConnection();
    $stmt = $db->prepare("SELECT DISTINCT S.station_id, S.name, SA.sub_area_name FROM dev.Station AS S INNER JOIN dbo.SubArea AS SA ON S.sub_area_id = SA.sub_area_id INNER JOIN data.MonthlyNormalData as MND ON MND.station_id = S.station_id WHERE sub_area_name = '$regions[$slt_nomStations]' AND value IS NOT NULL ORDER BY S.name ASC");
    $stmt->execute();

    $IDs = array();
    $names = array();
    $stations = array();
    $lastStationName = "";
    while ($row = $stmt->fetch())
    {
        if ($lastStationName != $row['name'])
        {
            array_push($names, $row['name']);
            array_push($IDs, $row['station_id']);

            $lastStationName = $row['name'];
        }
    }

    $stations = array_fill_keys($IDs, $names);

    $newJSArray = json_encode($stations);
    echo json_encode($newJSArray);
}

不幸的是,这不起作用,因为getStationList()函数的输出现在是这样的:"{\"6047\":[\"LA GRANDE RIVIERE A\"]}"。那么我将如何修改我的代码以生成我的<select>节点及其子<option>节点,其value属性设置为每个相应电台名称的ID?< / p>

1 个答案:

答案 0 :(得分:1)

为什么不喜欢

$arr = array()
while ($row = $stmt->fetch()) {
     $arr[$row['stationID']] = $row['stationName'];
}

您正在使用array_push,它不允许您为推送值指定密钥 - 您只需获得下一个更高的可用索引。所以不要使用数组_ *()函数,只需直接填入键/值对。