如何在php中通过关联数组循环数据

问题描述 投票:0回答:1

很抱歉这个问题,因为可能是一个愚蠢的问题,但在在这里提问之前,我尝试自己解决问题,我使用谷歌和这个网站来找到解决方案..

我有这段代码,可以从数据库中获取数据并将结果存储到数组中。然后在 foreach 循环中,我想打印该数组的内容,以使用值内的 id 和名称作为选项的名称来填充选择表单..

我不知道我做错了什么以及我错过了什么..

使用 print_r 函数我可以看到数组里面有什么,我可以看到有我需要的东西。我还计算元素的数量并在 for 循环周期中使用计数器,但我陷入了这一点..

你可以帮我吗?

$stmnt = $pdo->query($this->sql4);
$result = array();
$result = $stmnt->fetchAll(PDO::FETCH_ASSOC);
foreach (array_keys($result) as $key) {
    $value = $result[$key];
}    

$count = count($result);
print_r($result);

try{
    $stmnt = $pdo->query($this->sql5);
    $rows = $stmnt->fetchAll(PDO::FETCH_DEFAULT);
    foreach($rows as $row){
        $html .= "<tr>";
        $html .= "<td class='text-wrap'>" . $row['id'] . "</td>";
        $html .= "<td class='text-wrap'>" . $row['nome'] . "</td>";
        $html .= "<td class='text-wrap'>" . $row['tipologia'] . "</td>";
        $html .= "<td class='text-wrap'>" . $row['disponibilita'] . "</td>";
        $html .= "<td class='text-wrap'>";
        $html .= "<select>";
        for($i = 0; $i < $count; $i++){
            $html .= "<option value='" . $value['id'] . "'>" . $value['nome'] . "</option>";
        }
        $html .= "</select>";
        $html .= "</td>";
        $html .= "</tr>";
    }
php mysql arrays for-loop
1个回答
0
投票

创建选项时,您应该循环遍历

$result
。您的代码只是重复最后一个选项
$count
次。

foreach ($result as $option) {
    $value = $option['id'];
    $name = $option['nome'];
    $html .= "<option value='$value'>$name</option>";
}

不需要之前的

$value
变量,摆脱创建它的循环。

© www.soinside.com 2019 - 2024. All rights reserved.