Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取错误无法将标量值用作数组_Php_Arrays - Fatal编程技术网

Php 获取错误无法将标量值用作数组

Php 获取错误无法将标量值用作数组,php,arrays,Php,Arrays,我想生成介于0和1之间的随机数,并将它们推送到二维数组中。我得到一个错误: $arr[$i][$j] = $rand; 无法将标量值用作数组 这是我的代码: <?php $zero = $one = $rand = 0; $arr = array(array()); for($i = 0; $i < 5; $i++) { $arr[$i] = $rand; for($j = 0; $j < 10; $j+

我想生成介于0和1之间的随机数,并将它们推送到二维数组中。我得到一个错误:

$arr[$i][$j] = $rand;
无法将标量值用作数组

这是我的代码:

<?php 

    $zero = $one = $rand = 0;
    $arr = array(array());

    for($i = 0; $i < 5; $i++) {
            $arr[$i] = $rand;

        for($j = 0; $j < 10; $j++) {
            $rand = mt_rand(0,1);
            if ($rand == 0) {
                $one++;
            } else {
                $zero++;
            }
            $arr[$i][$j] = $rand;
            echo $arr[$i][$j];
        }
            echo "<br/>";
    }
?>

$arr[$i]
是一个标量值,因为您在此处为其分配了一个整数:

$arr[$i] = $rand;
这不是一个数组。但您试图像一个数组一样访问它,该数组抛出以下错误:

$arr[$i][$j] = $rand;

您需要将该值设置为数组,或者使用不同的变量来保存数组数据。但是你不能同时做这两件事。

这里:
$arr[$i]=$rand,如果我们进行第一次迭代,您可以:
$arr[0]=0
然后在第二个for循环中,您尝试使用值
0
作为数组并在其中存储某些内容,这当然不起作用。感谢您的解释!