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

时间:2015-09-04 18:51:06

标签: php

我正在创建一个计算售票数量的函数,这是我的代码:

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编写实际代码时,我遇到了2个错误:

对于行,$ticket[$m] = $tickets_info[$m];消息:未定义的偏移量:0

对于行,$row['Qty'] = $quantity[$n++];消息:未定义的偏移量:0

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

1 个答案:

答案 0 :(得分:1)

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

Route::get('/login', function() {
    return View::make('login.form');
});