Heim  >  Artikel  >  Backend-Entwicklung  >  php foreach中赋值 循环完成后 这个在数组内新赋值的变量就消失了么?

php foreach中赋值 循环完成后 这个在数组内新赋值的变量就消失了么?

WBOY
WBOYOriginal
2016-06-06 20:25:161376Durchsuche

代码

<code class="php">if(count($res) > 0){
    foreach( $res as $value){
        $timestamp = strtotime($str_replace('/','-',$value['time']));
        $data[] = [ $timestamp , $value['cumulativeNet']];
    }
}</code>

循环结束后打印 $data 显示 Undefined variable: data

求问如何在能使用这个 $data ?

回复内容:

代码

<code class="php">if(count($res) > 0){
    foreach( $res as $value){
        $timestamp = strtotime($str_replace('/','-',$value['time']));
        $data[] = [ $timestamp , $value['cumulativeNet']];
    }
}</code>

循环结束后打印 $data 显示 Undefined variable: data

求问如何在能使用这个 $data ?

注意看提示:未定义的变量$data

你的$res有值吗?

直接用 $data[] 这种方式是不严禁的,使用前应该先定义空数组:

<code class="php">if(count($res) > 0){
    $data = array();
    foreach( $res as $value){
        $timestamp = strtotime($str_replace('/','-',$value['time']));
        $data[] = [ $timestamp , $value['cumulativeNet']];
    }
}</code>

你的 $res 不是数组,应该是个字符串。
var_dump($res) 试试

循环前得先定义变量,而不是放在循环里面

$timestamp = strtotime($str_replace('/','-',$value['time'])); 里的$str_replace???
写错了吧?

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn