Domanda

Friends,

I am creating a drupal form (its my second one yay!) and I am pulling from the database information about Coursework. a very simple coursework_id and a coursework_name.

Now the usual format to populate a drop down menu in Drupal is as follows:

$form['selected'] = array(
       '#type' => 'select',
       '#title' => t('Selected'),
       '#options' => array(
          0 => t('No'),
         1 => t('Yes'),
       ),
       '#default_value' => $category['selected'],
       '#description' => t('Set this to <em>Yes</em> if you would like this category to be selected by default.'),
   );

I am trying to pass up my coursework_id and coursework_name in the #options part of the select form described above.

So far I have come up with this line of code:

foreach ($results as $result) {

            $courseworks = (array($result->coursework_id => $result->coursework_name));
}

This matches the required format of the Options but however I can only store one result:

Array
(
    [2] => Java Programming
)

How could I be able to somehow push the new results. I have tried array_push from PHP but it does seem to work for this case, it can as far as I understand only append a value.

Kind regards, -D

È stato utile?

Soluzione

You should simply try :

foreach ($results as $result) {
    $courseworks[$result->coursework_id] = $result->coursework_name;
}

Altri suggerimenti

Basically you are redefining $courseworks with every iteration of $results array. Try this instead;

$courseworks = array();
foreach ($results as $result) 
{
    $courseworks[] = (array($result->coursework_id => $result->coursework_name));
}

The following should do it for you. You define the array first and then create keys and assign the relative value:

$courseworks = array();
foreach ($results as $result) {
    $courseworks[$result->coursework_id] = $result->coursework_name;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top