简体   繁体   English

推入二维PHP数组

[英]Pushing into a 2 dimensional PHP array

Friends, 朋友们

I am creating a drupal form (its my second one yay!) and I am pulling from the database information about Coursework. 我正在创建一个drupal表单(这是我的第二个表单!),并且从数据库中获取有关Coursework的信息。 a very simple coursework_id and a coursework_name . 一个非常简单的coursework_idcoursework_name

Now the usual format to populate a drop down menu in Drupal is as follows: 现在,在Drupal中填充下拉菜单的常用格式如下:

$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. 我试图在上述选择表单的#options部分中传递我的coursework_id和coursework_name。

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. 我已经从PHP尝试过array_push,但是在这种情况下它确实起作用,据我了解,它只能附加一个值。

Kind regards, -D 亲切的问候,-D

You should simply try : 您应该尝试:

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

Basically you are redefining $courseworks with every iteration of $results array. 基本上,您需要在$results数组的每次迭代中重新定义$courseworks 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM