未定义的索引php错误,但var_dump显示它是定义

时间:2014-06-04 13:20:33

标签: php arrays

我收到此错误:

Notice: Undefined index: id in /home/theclear/public_html/what/adminz/includes/func.inc.php on line 245
Notice: Undefined index: name in /home/theclear/public_html/what/adminz/includes/func.inc.php on line 246
Notice: Undefined index: state in /home/theclear/public_html/what/adminz/includes/func.inc.php on line 247
Notice: Undefined index: id in /home/theclear/public_html/what/adminz/includes/func.inc.php on line 250

var_dump告诉我:

array(2) { [0]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(10) "killswitch" ["state"]=> string(1) "1" } [1]=> array(3) { ["id"]=> string(1) "2" ["name"]=> string(8) "readonly" ["state"]=> string(1) "0" } } 

功能内容:

global $dbh;
$stmt=$dbh->prepare("SELECT * FROM `1_bolean_settings`");
$stmt->execute();
while ($set = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
var_dump($set);
$col1 = $set['id'];
$col2 = $set['name'];
$col3 = $set['state'];
if ($col3 == '1') {$state = 'checked';}
else {$state = 'unchecked';}

echo '                               
<div class="onoffswitch">
<input type="checkbox" name="'.$col1.'" class="onoffswitch-checkbox" id="myonoffswitch" '.$state.'>
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div> ';

}

因此,如果var_dump($set);显示["id"]=> string(1),那么为什么$set['id']会给我一个未定义的索引错误?

2 个答案:

答案 0 :(得分:2)

这是一个嵌套数组。这意味着您寻求的数据有两个层次:

$col1 = $set[0]['id'];
$col2 = $set[0]['name'];
$col3 = $set[0]['state'];

答案 1 :(得分:0)

你var_dump显示你有2个结果(所以变量中有2个数组)。

要访问例如第一个结果,您必须使用:

$col1 = $set[0]['id'];

或者您可以使用循环,或使用:

$stmt->fetch(...);

如果你想只有一行;