有人可以帮助我调试这个错误:未定义的偏移量:0


Can someone help me debug this error: Undefined offset: 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生成的二维数组,其结构如下:

$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编写真正的代码时,我得到了两个错误:

For line, $ticket[$m] = $tickets_info[$m]; Message: Undefined offset: 0

For line, $row['Qty'] = $quantity[$n++]; Message: Undefined offset: 0

我不知道为什么没有索引0,也许我没有正确初始化数组,或者我没有以正确的格式传递$ticket_info中的数据?谁能帮我看看这段代码?

在尝试访问该索引之前请检查:

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