关联数组错误

时间:2013-12-27 15:52:36

标签: php mysql associative-array

我不想从MySQL创建一个JSON php输出,该数据库至少包含以下内容 用户名,日期时间,acctsessiontime

我的逻辑包括 $ key ,即上的用户名和ASSOC数组,但是 用户名在末尾包含2个额外的字符_1,_2,_3等....

$rows = array();
$acctsessiontime=0;
while ($row = mysql_fetch_assoc($result)) {
        $key=substr($row['username'], 0, -2);
        $acctsessiontime+=round($row['acctsessiontime']/60*.20,2);
        $acctsessiontimeby[$key]+=$acctsessiontime;
        $datetime=$row['datetime'];
        $rows[$key][] = "[$datetime,$acctsessiontimeby[$key]]";
        $rows['All'][]= "[$datetime,$acctsessiontime]";
}

php错误:
注意:未定义的偏移量: \ xampp \ htdocs \ intercall \ scripts \ server_processing2.php 中的 77

$acctsessiontimeby[$key]+=round($row['acctsessiontime']/60*.20,2);

值:

$row['username'] /// output user1_1
$key // output user1
$acctsessiontime // output the $$$ calculated a 60seg in a min and 0.20$ by min
$acctsessiontimeby[$key]+=round($row['acctsessiontime']/60*.20,2);

1 个答案:

答案 0 :(得分:0)

正如Leonardo所说,您必须先将$acctsessiontimeby定义为数组。 但并非全部。 $acctsessiontimeby[$key]+=运算符引用'$ acctsessiontimeby [$ key]'中的值。当密钥不存在时,PHP会抛出错误。

首先,您应该检查密钥是否存在,而不是:

$acctsessiontimeby[$key]+=round($row['acctsessiontime']/60*.20,2);

你应该写:

$acctsessiontimeby = array(); // before while loop

// ...

if( isset( $acctsessiontimeby[$key] ) ){
    $acctsessiontimeby[$key]+=round($row['acctsessiontime']/60*.20,2);
} else {
    $acctsessiontimeby[$key]=round($row['acctsessiontime']/60*.20,2);
}