PHP注意:未定义的变量:str

时间:2016-02-11 17:10:58

标签: php

我的代码

function rand_string($length) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ]; // this line error 
 }
return $str;
}

错误

  

PHP注意:未定义的变量:第5行的str ...

2 个答案:

答案 0 :(得分:0)

来吧,这很简单:

with sample_data as (select 1 id, to_date('12/03/2015', 'dd/mm/yyyy') time from dual union all
                     select 2 id, to_date('23/04/2014', 'dd/mm/yyyy') time from dual union all
                     select 2 id, to_date('01/12/2014', 'dd/mm/yyyy') time from dual union all
                     select 1 id, to_date('01/12/2015', 'dd/mm/yyyy') time from dual union all
                     select 3 id, to_date('05/11/2015', 'dd/mm/yyyy') time from dual)
-- End of creating a subquery to mimick a table called "sample_data" containing your input data.
-- See SQL below:
select yr,
       id most_frequent_id,
       cnt_id_yr cnt_of_most_freq_id
from   (select   to_char(time, 'yyyy') yr,
                 id,
                 count(*) cnt_id_yr,
                 dense_rank() over (partition by to_char(time, 'yyyy') order by count(*) desc) dr
        from     sample_data
        group by to_char(time, 'yyyy'),
                 id)
where  dr = 1;

YR   MOST_FREQUENT_ID CNT_OF_MOST_FREQ_ID
---- ---------------- -------------------
2014                2                   2
2015                1                   2

答案 1 :(得分:0)

您正在将字符串“添加”到未知变量 $ str 线

 $str .= ....

是罪魁祸首。 。=是字符串连接。长形将是

$str = $str . "whatEver";

这是在后台发生的,这就是PHP提供未定义变量通知的原因。

要删除此通知,您只需在连接变量之前声明该变量。

function rand_string($length) {
    $str = "";

现在已知$ str,可以添加更多字符串。