0

我在undefined index: position使用下面的代码时遇到了错误,但我在做的任何事情中都看不到任何错误。看起来就像 php 页面上的示例(http://php.net/manual/en/control-structures.foreach.php):

$position_list = array(
1 => "Chair", 
2 => "SACA",
5 => "School",
0 => "Disabled",
);

foreach ($position_list as $priv_id=>$position) {
    $data['position'] .= '<option value="'.$position_list[$priv_id].'"'; //throws error here
     if ($position_list[$priv_id] == $privilege_id) {
            $data['position'] .= " selected=\"selected\""; 
        }
     $data['position'] .= '>'.$position.'</option>';   //throws error here
}   

我评论了引发错误的代码。

编辑: $data['position'] 是完全不同的东西,它不是指在 foreach 数组中使用的位置。

Edit2:更多代码。这是这个 php 文件末尾的内容:

$page->html .= File::text_replacement( "add_user.inc", $data );

在 add_user.inc 文件中,我有这样一行:

<td><select name="privilege_id">%%position%%</select></td>

%%position%%将在调用 File 类时被 $data['position'] 变量替换。这并不意味着是 $position。

4

3 回答 3

1

$data['position'] probably isn't defined. You *probably* mean$data[$position]

$data['position']在循环之前定义:

$data['position'] = '';
foreach ($position_list as $priv_id=>$position) {
于 2013-05-02T17:29:04.183 回答
1

$data需要是一个数组,并且由于您要将字符串值附加到$data['position'],因此需要首先定义索引“位置”,请尝试:

$position_list = array(
1 => "Chair", 
2 => "SACA",
5 => "School",
0 => "Disabled",
);

if (!is_array($data)){//making sure $data is an array
    $data = array();
}
$data['position'] = '';//Creating the index 'position' before using it.
foreach ($position_list as $priv_id=>$position) {
    $data['position'] .= '<option value="'.$position_list[$priv_id].'"'; //throws error here
     if ($position_list[$priv_id] == $privilege_id) {
            $data['position'] .= " selected=\"selected\""; 
        }
     $data['position'] .= '>'.$position.'</option>';   //throws error here
}
于 2013-05-02T17:34:50.710 回答
0

您正在使用变量 $priv_id=>$position。它应该是 $data[$position] 而不是 $data['position']。您应该将您的代码更改为:-

foreach ($position_list as $priv_id=>$position) {
    $data['$position'] .= '<option value="'.$position_list[$priv_id].'"'; //throws error here
     if ($position_list[$priv_id] == $privilege_id) {
            $data['$position'] .= " selected=\"selected\""; 
        }
     $data['$position'] .= '>'.$position.'</option>';   //throws error here
}   
于 2013-05-02T17:30:55.070 回答