Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to cycle data through an associative array in php

sorry for the question because probably is a silly question but before asking here i tried by myself to solve the problem and i used Google and this site to find a solution..

I have this piece of code that fetch data from a database and store the result into an array. Then inside a for each loop i would like to print the content of this array to populate a select form with the id inside the value and the name as the name of the option..

I don’t know what i am doing wrong and what i am missing..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using print_r function i can see what’s inside the array and i can see that there is what i need. I also count the number of the element and use the counter after in the for loop cycle but i am stuck at this point..

May you help me please?

$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>";
    }

>Solution :

You should be looping through $result when creating the options. Your code is simply repeating the last option $count times.

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

There’s no need for the earlier $value variable, get rid of the loop that creates it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading