php中数组的未定义偏移量

时间:2015-05-22 09:17:24

标签: php

我有以下代码:

$count_table = array();
foreach ($events_tab as $event) {
    if(isset($event["nature"])){
        $count_table[$event["nature"]]++;
    }

}

数组events_tab是这样的:

Array
(
     [0] => Array
       (
        [nature] => 300
        [id] => 100828698
    )

[1] => Array
    (
        [nature] => 3001
        [id] => 100828698
    )

)

我收到错误:未定义的偏移量:此行中为300:$count_table[$event["nature"]]++;。请帮我!! Thx提前!!

2 个答案:

答案 0 :(得分:2)

$count_table = array();
foreach ($events_tab as $event) {

    if(isset($event["nature"])){
        if(!isset($count_table[$event["nature"]])){
            $count_table[$event["nature"]]=0;
        }
        $count_table[$event["nature"]]++;
    }
}

答案 1 :(得分:0)

检查$count_table是否设置了密钥。它应该是 -

if(isset($count_table[$event["nature"]])){
    $count_table[$event["nature"]]++;
} else {
    $count_table[$event["nature"]] = 0;
}