为什么我收到错误消息“注意:未定义的索引:格式..“在 PHP 中


Why I get an error message "Notice: Undefined index: formats ..." in php?

当我运行我的PHP代码时,它给出了一条错误消息" Notice: Undefined index: formats in C:'xampp'htdocs'playit2'scripts'session.php on line 39 "。

这是我的HTML代码。

$my_items = array();
$jsql_e = mysql_query("select request_list.id, request_list.formats, request_list.product_id, request_list.sent_on, request_list.return_on, products.name, products.certificate from request_list, products where request_list.email='$visit_email' and request_list.sent='1' and request_list.returned='1' and products.id=request_list.product_id") or die(mysql_error());
$jarr_rent_list_history = array();
while($jfet_e = mysql_fetch_assoc($jsql_e)){
    $jfet_e = array_filter($jfet_e);
    if(count($jfet_e) > 0){ array_push($jarr_rent_list_history, $jfet_e); }
}
foreach($jarr_rent_list_requested as $item_arr){
    if((count($item_arr) > 0) && (strlen($item_arr['product_id']) > 0)){
        array_push($my_items, $item_arr['product_id'], $item_arr['formats']);
    }
} 

错误在"if((count($item_arr) > 0) && (strlen($item_arr['product_id']) > 0)){"和"格式"是id类型。

首先,你的问题不正确。如果您遇到Notice: Undefined index: formats in C:'xampp'htdocs'playit2'scripts'session.php on line 39错误。我的猜测是关于线路array_push($my_items, $item_arr['product_id'], $item_arr['formats']).

答案本身几乎就是你得到的错误。数组$item_arr中不存在键formats

最好通过执行以下操作来检查这一点:

array_push($my_items, $item_arr['product_id'], ( isset($item_arr['formats']) ? $item_arr['formats'] : null)

这样,格式值将设置为 null(如果不存在)。

未定义的索引完全符合它所说的意思。

$item_arr['formats']未定义。您应该在使用前检查它是否是。

根据您的情况,这可能会起作用。你能处理空formats吗?

$item_arr['formats'] = (isset($item_arr['formats']))?$item_arr['formats']:"";