2012-12-04 47 views
1

試圖解構一個函數我收到一個警告通知,用於從數據庫中檢索CSV數據。PHP:在urldecode/explode中未定義偏移

功能是從index.php文件調用,並且可以被格式化爲

$masterRecords = $qb->genResultsTable($qid, $config[27]);

$config[27]是動態設置的,而是來幫助理解;它是一個以週期爲單位的整數列表。例如"3.4.5.6.7.8.9.25.141.137.83"
$qid是一個整數 - 例如, "63"

該函數的工作原理,但我想看看如果我可以擺脫php通知。

Notice: Undefined offset: 106 in /vagrant/public/arc/inc/lib.php on line 522 

調用堆棧:
爲每個項目獲得通知通過循環傳遞

1 0.0028 417156 {main}() ../index.php:0 
2 1.2886 473280 qb->genResultsTable() ../index.php:66 

功能:

public function genResultsTable($qid, $clist) { 
    $url = "{$this->qb_ssl}{$this->db_id}?act=API_GenResultsTable&ticket={$this->ticket}&apptoken={$this->app_token}&qid={$qid}&clist={$clist}&slist={$clist}&options=csv"; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cjFile); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, $this->ckfile); 
    // curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10); 
    curl_setopt($ch, CURLOPT_COOKIE, "TICKET=" . urlencode($this->ticket)); 
    $r = curl_exec($ch); 
    $r = preg_replace_callback('/([\'"])([^"]+)\1/', 'call_back', $r); 
    preg_match_all('/(.*)\r\n/', $r, $matchs); 
    $fields = explode('.', $clist); 
    $count = count($matchs[0]); 
    $arrs = array(); 
    for ($i = 1; $i < $count; $i++) { 
    $explode_arr = explode(',', $matchs[0][$i]); 
    $arr = array(); 
    foreach ($fields as $key => $field) { 
    // vv THIS BELOW LINE IS THE LINE THAT IS INDICATED IN ERROR vv 
     $arr[$field] = urldecode($explode_arr[$key]); 
    } 
    $arrs[] = $arr; 
    } 
    return $arrs; 
} 

function call_back($matches) { 
    return urlencode($matches[0]); 
} 
+0

函數的工作原理,所以我只是想知道,每行的$鍵是未定義的,它對函數的結果沒有任何影響? '偏移未定義'錯誤會對代碼性能產生影響嗎? – user1874512

+1

總是使用'isset()'來防止這種錯誤... – HamZa

回答

0

爲了使@哈姆扎的答案更清楚的是,基本上你收到通知的原因是因爲ause你正在訪問一個索引不存在,或沒有設置的數組...

理想情況下,每次你使用帶變量鍵的[]時,最好測試一下鍵索引/鍵存在於該數組中。

所以,簡單地將doSomeThing($arr[$x])

if(isset($arr[$x])){ 
    doSomeThing($arr[$x]) 
} 

這將阻止無效的數組訪問,並通知應消失。