Jump to content

Trouble using foreach with associative array


chrscote
Go to solution Solved by mac_gyver,

Recommended Posts

I am writing a small page in which I want a combo box giving a list of options taken from a database table where the ID from the table is the value and the string is the actual option.  I am trying to set it up using a foreach statement, but I keep getting the following error message:  Notice: Array to string conversion in issue.php on Line 87.

 

Here is the code I'm using to create this array.

First, this is in the beginning of the file to get the array:

$sqlStatuses = "SELECT StatusID, Status FROM Status";
try {
	$rsStatuses = $db->query($sqlStatuses);
	$arrAllStatus = $rsStatuses->fetchAll();
} catch (Exception $e) {
	echo $e->getMessage();
}

Then in the page body, I am using:

<select id="status">
    <?php
        foreach ($arrAllStatus as $statID=>$status) {
            echo "<option value=\"$statID\"$selected>$status</option>";
        }
    ?>
</select>

The errors I am getting are on the echo line.  Do the variables I use after the "as" have to be the same as the fields in the table?  I didn't think so.

 

 

Chris

Link to comment
Share on other sites

  • Solution

the ->fetchAll() method returns an array of arrays. in your foreach() loop, $status is an array holding the data for each row. $statID will just be the zero referenced numerical array indexes of the main array.

 

using foreach ($arrAllStatus as $row) { would perhaps be clearer. you would then reference the two columns you have selected using - $row['StatusID'] and $row['Status']

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.