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

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

WBOY
WBOYOriginal
2016-06-06 20:25:161414browse

代码

<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???
写错了吧?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn