简体   繁体   中英

Undefined index notice even though i can get the data

I'm working with an array that gives me all the info if print_r but it also says that it is an unidentified index. Code:

    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

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 ) ) 

die($x): 1

Should i hide this notice with @ or is there any way to solve this? (Sorry for the portuguese words)

Since you are in a foreach loop you don't have to use index 0 . foreach auto increment the index, so on next index 0 is undefined

Please try without index or put $x out of loop

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

or

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

Give it a try

The problem was an error with my code:

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

Where is id_extra it should be id_refeicao. Thank you for your time and help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM