Php 如何使用查找表?

Php 如何使用查找表?,php,mysql,drupal,drupal-7,Php,Mysql,Drupal,Drupal 7,我使用下面的代码将am_category表中的所有类别放入表单中的下拉框中。它起作用了。但是在提交表单时,我需要category.ID而不是名称。通常如何处理像这样的查找表 $category_result = db_query("SELECT id, name FROM {am_category}"); $categories = array(); foreach($category_result as $row) { $categories[$row->id] = t($row

我使用下面的代码将am_category表中的所有类别放入表单中的下拉框中。它起作用了。但是在提交表单时,我需要category.ID而不是名称。通常如何处理像这样的查找表

$category_result = db_query("SELECT id, name FROM {am_category}");
$categories = array();
foreach($category_result as $row)
{
    $categories[$row->id] = t($row->name);
}   

$form['category_options'] = array( 
'#type' => 'value', 
'#value' => $categories
); 
$form['category']['category'] = array( 
'#title' => t('Category'), 
'#type' => 'select', 
'#description' => t('Please select the category of this achievement.'), 
'#options' => $form['category_options']['#value'] 
);

在提交函数中传递到
$form_state
数组的值将是ID而不是名称,它将是下拉列表中选项的键,而不是值

如果您想稍微缩短代码,可以使用数据库查询的方法自动构建类别数组。您不需要
category\u options
元素,因为您已经可以在提交函数的
$form
变量中访问该数组

另外,我会小心地将外部元素和内部元素命名为相同的名称(
category
),这可能会导致一些问题

此代码应有助于:

function mymodule_myform($form, &$form_state) {
  $categories = db_query("SELECT id, name FROM {am_category}")->fetchAllKeyed();

  $form['category_wrapper']['category'] = array(
    '#type' => 'select',
    '#title' => t('Category'),
    '#description' => t('Please select the category of this achievement.'),
    '#options' => $categories
  );

  return $form;
}

function mymodule_myform_submit(&$form, &$form_state) {
  $selected_category_id = $form_state['values']['category'];

  // Just in case you wanted to know, this would get the corresponding name for the selected category:
  $selected_category_name = $form['category_wrapper']['category']['#options'][$selected_category_id];
}

谢谢正是我想要的。