【问题标题】:store variables in an mutidimensional array?将变量存储在多维数组中?
【发布时间】:2015-12-08 12:04:11
【问题描述】:

我尝试将在 while 循环中设置的变量存储在多维数组中。 Afterwarts 我想把数组打印出来。

我做了什么:

$counter = 0;
while($counter < 10){
    $a = $counter + 10;
    $b = $counter + 5;
    $file_ar[] = array($a,$b);
    $counter++;
}

/* $file_ar[1-10] = "$a","$b" */

$i = 0;
while(isset($file_ar[$i])) {
    $a = $file_ar[$i][0];
    $b = $file_ar[$i][1];

    echo $a.' is not '.$b;
}

当我运行这段代码时,我什么也得不到。

这是什么原因?

谢谢!

【问题讨论】:

  • while(isset($file_ar[$i])) {} 可能是问题所在。 var_dump($file_ar) 给你什么,你想要的结果是什么?
  • 你的 while 循环如何结束?

标签: php arrays loops store


【解决方案1】:

这是代码-

<?php
$counter = 0;
while($counter < 10){
    $a = $counter + 10;
    $b = $counter + 5;
    $file_ar[] = array($a,$b);
    $counter++;
}
/* $file_ar[1-10] = "$a","$b" */

$i = 0;
while(isset($file_ar[$i])) {
    $a = $file_ar[$i][0];
    $b = $file_ar[$i][1];

    echo $a.' is not '.$b;
    $i++;
}

【讨论】:

    【解决方案2】:

    您需要添加要添加的数组的索引,或者您只是在覆盖它。

    $counter = 0;
    while($counter < 10){
        $a = $counter + 10;
        $b = $counter + 5;
        $file_ar[$counter] = array($a,$b);
        $counter++;
    }
    
    $i = 0;
    while(isset($file_ar[$i])) {
        $a = $file_ar[$i][0];
        $b = $file_ar[$i][1];
        if ($a != $b)
            echo $a.' is not '.$b;
        else
            echo $a.'='.$b;
        $i++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 2011-06-10
      • 2019-08-08
      • 2021-03-27
      • 1970-01-01
      • 2013-09-04
      • 2016-05-12
      相关资源
      最近更新 更多