未定义索引php错误,但var_dump显示它已定义
我收到这个错误:未定义索引php错误,但var_dump显示它已定义,php,arrays,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
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> ';
}
global$dbh;
$stmt=$dbh->prepare(“从'1\u bolean\u settings`中选择*”;
$stmt->execute();
而($set=$stmt->fetchAll(PDO::FETCH_ASSOC)){
var_dump($set);
$col1=$set['id'];
$col2=$set['name'];
$col3=$set['state'];
如果($col3='1'){$state='checked';}
else{$state='unchecked';}
回声'
';
}
因此,如果
var\u dump($set)
正在显示[“id”]=>字符串(1)
那么为什么$set['id']
给我一个未定义的索引错误?它是一个嵌套数组。这意味着您所寻找的数据有两个层次:
$col1 = $set[0]['id'];
$col2 = $set[0]['name'];
$col3 = $set[0]['state'];
var_dump显示有2个结果(因此变量中有2个数组) 例如,要访问第一个结果,您必须使用:
$col1 = $set[0]['id'];
也可以使用循环,或使用:
$stmt->fetch(...);
如果只想有一行 你能告诉我为什么要得到嵌套数组吗?我以相同的方式存储和选择members表中的用户,并且我为他们返回的数组不嵌套。如果查询中有多个结果,则返回的数组不嵌套。如果您只希望返回一个结果,则应将查询限制为一个结果。虽然您的建议解决了我发现的问题,但使用foreach循环而不是while循环解决了嵌套数组的问题。