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

时间:2014-10-01 11:31:59

标签: php arrays notice

我正在使用一个数组,该数组为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

我应该用@隐藏此通知还是有办法解决这个问题? (对不起葡萄牙语)

2 个答案:

答案 0 :(得分:0)

由于您处于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

试一试

答案 1 :(得分:0)

问题是我的代码错误:

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

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