Foreach循环;未定义的索引:位置。但语法看似正确

时间:2013-05-02 17:27:57

标签: php

我使用下面的代码收到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>
在调用File类时,

%%position%%将被$ data ['position']变量替换。这不是$ position。

3 个答案:

答案 0 :(得分:1)

$数据[ '位置'] probably isn't defined. You *probably* mean $数据[$位置]

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

$data['position'] = '';
foreach ($position_list as $priv_id=>$position) {

答案 1 :(得分:1)

$data需要是一个数组,因为你要将字符串值附加到$data['position'],所以需要首先定义索引'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
}

答案 2 :(得分:0)

您正在使用变量$ priv_id =&gt; $ 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
}