为动态下拉列表重建数组

时间:2018-07-17 17:40:09

标签: php

我试图获取查询结果,并构建到一个关联数组中,在该数组中,我将高层用于常规下拉菜单,并且该下拉菜单选择将加载数组的对应子级。

我当前的功能:

$getDisplays = "
SELECT *
FROM locations l
inner join displays d
ON d.location_id = l.id;";

$displayResult = $mysqlConn->query($getDisplays);

这将返回:

Array
(
[ID] => 1
[location_name] => Office 1
[display_name] => lobby
[location_id] => 1
)
Array
(
[ID] => 2
[location_name] => Office 1
[display_name] => break room
[location_id] => 1
)
Array
(
[ID] => 3
[location_name] => Office 2
[display_name] => lobby
[location_id] => 2
)
Array
(
[ID] => 4
[location_name] => Office 2
[display_name] => break room
[location_id] => 2
)
Array
(
[ID] => 10
[location_name] => Office 5
[display_name] => Break Room
[location_id] => 5
)
Array
(
[ID] => 11
[location_name] => Office 5
[display_name] => Lobby
[location_id] => 5
)
Array
(
[ID] => 12
[location_name] => Office 5
[display_name] => Conference Room
[location_id] => 5
)

我正在尝试创建动态下拉列表,以便第一个下拉列表显示每个不同的location_name,并且根据选择,第二个下拉列表包含相应的display_name。

因此对于此数组,第一个下拉列表将具有:

<option>Office 1</option>
<option>Office 2</option>
<option>Office 5</option>

如果我选择Office 1,则下一个下拉列表将包含:

<option>lobby</option>
<option>break room</option>

我现在构建它们的方式:

<label for="plantSelect">Select A Location</label>
<select class="form-control" id="plantSelect">
    <?php foreach($displayResult as $area=>$display):?>
    <option><?php echo $display['location_name']?></option>
    <?php endforeach;?>
</select>

<label for="areaSelect">Select An Area</label>
<select class="form-control" id="areaSelect">

    <option>Please Choose a Location</option>

</select>

问题是,第一个下拉列表显示每个条目,因此它显示了Office 1,Office 2和Office 5的多个实例。我希望它仅显示每个位置名称中的一个,然后在下一个下拉列表中加载子项( display_name)。我还需要显示中的ID才能将其保存到数据库中,因此我在考虑解决此问题后应该可以将其包含在表单中。

我在做什么数组错误?

2 个答案:

答案 0 :(得分:1)

您可以像这样重建阵列:

$displayNames = array();
foreach($displayResult as $subArray) {
  if(!array_key_exists($subArray['location_name'], $displayNames)) {
    $displayNames[$subArray['location_name']] = array();

  }
    $displayNames[$subArray['location_name']][] = $subArray['display_name'];
}

现在,您可以执行以下操作:

<?php foreach($displayNames as $displayName):?>
<option><?php echo key($displayName['location_name'])?></option>
<?php endforeach;?>

事情不会重复。另外,现在您可以轻松创建其他下拉菜单。

答案 1 :(得分:0)

$displayNames = array();
foreach($displayResult as $subArray) {
  if(!array_key_exists($subArray['location_name'], $displayNames)) {
      $displayNames[$subArray['location_id']]['location'] = $subArray['location_name'];
      $displayNames[$subArray['location_id']]['display_name'] = array();
  }

  array_push( $displayNames[$subArray['location_id']]['display_name'], array($subArray['ID'] => $subArray['display_name']));
}

print_r($ displayNames);