PHP foreach array into option value

PHP foreach array into option value

不需要提供太多有关正在使用的 API 的信息,我正在尝试获取 选项值 以匹配选项标签中包含的内容.

像这样:

<option value="Foo">Bar</option>

这是PHP:

<?php
    $counter = 0;
    $numbers = $client->account->available_phone_numbers->getList('US', 'Local', array(
    "AreaCode" => $_POST["areacode"]));
    echo "<select>";
    foreach($numbers->available_phone_numbers as $number) {
        echo "<option value=''>";
        echo $number->phone_number;
        $counter++;
        echo "</option>";
        echo "<br>";
    }
    echo "</select>";
    echo "<br>";
    echo $counter;
?>

使用这种形式:

<form action="index.php" method="post">
    Area Code:<br>
    <input type="text" name="areacode" value=""><br>
    <input type="submit" value="Submit">
</form>

echo "<option value=''>";更改为echo "<option value='{$number->phone_number}'>";

您的语法不正确。

echo '<select>';
foreach($numbers->available_phone_numbers as $number) {

    echo '<option value="' .$number->phone_number .'">';
    echo $number->phone_number;
    echo '</option>';
}
echo '</select>'; 

此外,您的 select 元素中不应包含 br 标签。

我认为您需要将 select 移到表单标签内,以便也提交 selected 数据。

<form action="index.php" method="post">
echo "<select>";
foreach($numbers->available_phone_numbers as $number) {

echo "<option value='".$number->phone_number."'>";
echo $number->phone_number;
$counter++;
echo "</option>";
echo "<br>";
}
echo "</select>";
echo "<br>";
echo $counter;
?>Area Code:<br>
<input type="text" name="areacode" value=""><br>
<input type="submit" value="Submit">
</form>

希望对您有所帮助

<?php
$counter = 0;
$numbers = $client->account->available_phone_numbers->getList('US', 'Local',        
array(
"AreaCode" => $_POST["areacode"]
));
?>
<form action="index.php" method="post">
<?php
echo "<select>";
foreach($numbers->available_phone_numbers as $number) {
echo "<option>" . $number->phone_number . "</option>";
$counter++;
}
echo "</select>";

?>
<input type="submit" value="Submit">
</form>