未定义的索引通知,即使我可以获得数据


Undefined index notice even though i can get the data

我正在使用一个数组,该数组提供了if print_r的所有信息,但它也表示它是一个未识别的索引。代码:

    foreach ($_SESSION['passo4'] as $key => $value) {
        $x = $data_ref[0]['tipo_refeicao']; //gives me the error
        echo $x; //echoes 1
        print_r($data_ref);
        if($key != 'preco'){
            //Obter info do tipo de vestuário
            $f_r = $dbh->prepare("SELECT tipo_refeicao, preco_acompanhante, preco_participante FROM refeicao WHERE id_extra = '$key'");
            $f_r->execute();
            $data_ref = $f_r->fetchAll();
            echo "<tr><td>".
            datasearch($data_tref, 'tipo_refeicao', $x, 'descricao')
            ."</td>";
            echo "<td>". $value ."</td>";
            echo "<td>". $data_ext[0]['preco'] * $value ."€</td></tr>";
        }
    }

通知

Notice: Undefined offset: 0 in C:'xampp'htdocs'Rot.Aventura'eventos'passo5.php on line 96

Print_r($data_ref):

Array ( [0] => Array ( [id_refeicao] => 4 [id_evento] => 11 [tipo_refeicao] => 1 [preco_participante] => 5 [preco_acompanhante] => 6 [limite_pessoa] => 2 ) ) 

骰子($x):1

我应该用@隐藏这个通知吗?或者有什么办法解决这个问题吗?(对不起葡萄牙语单词)

由于您处于foreach循环中,因此不必使用索引0foreach自动递增索引,因此下一个索引0是未定义的

请在没有索引的情况下尝试或将$x放入循环外

foreach ($_SESSION['passo4'] as $key => $value) {
    ...
    $data_ref = $f_r->fetchAll();
    $x = $data_ref['tipo_refeicao']; //gives me the error

foreach ($_SESSION['passo4'] as $key => $value) {
...
$x = $data_ref['tipo_refeicao']; //gives me the error

试试

问题是我的代码出现错误:

$f_r = $dbh->prepare("SELECT tipo_refeicao, preco_acompanhante, preco_participante FROM refeicao WHERE id_extra = '$key'");

id_extra在哪里?它应该是id_refeicao。感谢您的时间和帮助