2015-09-04 59 views
0

我創建計算售出票的數量的函數,並且在這裏是我的代碼:有人可以幫我調試這個錯誤:未定義的偏移量:0?

public function get_quantity($tickets_info){ 
    $i = 0; //$i is the starting point of the loop 
    $k = 0; 
    $Qty = 1; // this is used to save the quantity of tickets, by default there is always one ticket 
    $index = array(); 
    $quantity = array(); 
    for($j = 1; $j < count($tickets_info); $j++) { 
//   if the ticket_id are the same, then increase the quantity by one 
     if($tickets_info[$i]['ticket_id'] == $tickets_info[$j]['ticket_id']) 
     { 
      $Qty++; 
     } 
//   if the ticket_id are not the same, then push the quantity into an array and remember the index 
     else 
     { 
      $idx = $j;//remember the index of the next first different ticket_id 
      $i = $j;//find the next starting point 
      $index[$k] = $idx;//push back the index of the next different ticket_id 
      $quantity[$k] = $Qty;//save quantity into the array 
      $k++;//increase the index poniter 
      $Qty = 1;//reset quantity back to one 
     } 
    } 
//  push the last quantity into the array 
    $quantity[$k+1] = $Qty; 

    //assign the ticket information into a new array 
    for($m = 0; $m < count($quantity); $m++){ 
     $ticket[$m] = $tickets_info[$m]; 
    } 

    //create the finally array, combine ticket information with quantity 
    $n = 0; 
    foreach($ticket as $row) 
    { 
     $row['Qty'] = $quantity[$n++]; 
    } 

    return $ticket; 

} 

$ticket_info是從一個SQL生成的2-d陣列,它有這樣的結構:

$ticket_info 
(
    [0]=>array 
    (
     [ticket_id] => 0001 
     [purchase_time] => 2014/01/02 
     .... 

    ) 
    [1]=>array 
    (
     [ticket_id] => 0001 
     [purchase_time] => 2014/01/02 
     .... 

    ) 
    [2]=>array 
    (
     [ticket_id] => 0001 
     [purchase_time] => 2014/01/02 
     .... 

    ) 
    .... 
) 

基本上,如果門票有相同ticket_id,這意味着他們在同一時間被買走(但在數據庫中,我分別記錄他們爲特定目的),所以我需要他們加起來和獲得數量。

我不熟悉PHP數組,所以我用C++編寫我的算法並對其進行了測試。它工作正常。然而,當我試圖用PHP編寫真正的代碼,我得到了2個錯誤:

對於線,$ticket[$m] = $tickets_info[$m];消息:未定義抵消:0

對於線,$row['Qty'] = $quantity[$n++];消息:未定義抵消:0

我不知道爲什麼沒有索引0,也許我沒有正確初始化數組,或者我沒有以正確的格式傳遞$ticket_info中的數據?有人可以幫我看看這段代碼嗎?

+0

所以'的var_dump($票,$ tickets_info)',看看你真的處理。未定義的偏移量意味着您試圖訪問不存在的數字索引。 –

+0

@MarcB感謝您的建議。 '$ ticket_info'爲空。我沒有成功將這些數據傳遞給函數 –

回答

1

做一次檢查您嘗試訪問之前指數:

if (!empty($ticket) && !empty($tickets_info)) { 
    $ticket[$m] = $tickets_info[$m]; 
}