Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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中为二维(2D)数组获取用户输入?_Php_Arrays - Fatal编程技术网

如何在php中为二维(2D)数组获取用户输入?

如何在php中为二维(2D)数组获取用户输入?,php,arrays,Php,Arrays,我对PHP完全陌生,无法理解如何接受二维数组(2D数组)的用户输入。我正在为你提供我一直在尝试的代码。有人能帮我吗 <?php //$handle = fopen ("php://stdin","r"); $n= 0; $m= 0; fscanf("%d", $n); fscanf("%d", $m); $a = array(n)(m); for($i=0 ; $i < $n ; $i++){ for($j=0 ; $j < $m ; $j++ ){

我对PHP完全陌生,无法理解如何接受二维数组(2D数组)的用户输入。我正在为你提供我一直在尝试的代码。有人能帮我吗

<?php

//$handle = fopen ("php://stdin","r");
$n= 0;
$m= 0;
fscanf("%d", $n);
fscanf("%d", $m);
$a = array(n)(m);
for($i=0 ; $i < $n ; $i++){
    for($j=0 ; $j < $m ; $j++ ){
        fscanf("%d", $a[$i][$j]);
    }
}


//fclose($handle);
?>


我希望获取输入并打印数组

这是经过测试的片段

$f    = fopen('php://stdin', 'r');
// read whole string for manipulation
$line = fgets($f);
// exploding data with spaces
$arr  = explode(" ", $line);
$m    = $arr[0]; // first int as m rows 
$n    = $arr[1]; // second int as n cols
// unsetting as they are already used
unset($arr[0]);
unset($arr[1]);
// resetting index of array
$arr    = array_values($arr);
$result = [];

for ($i = 0; $i < $m; $i++) {
    for ($j = 0; $j < $n; $j++) {
        // fetching current value of array
        $result[$i][$j] = current($arr);
        // moving iterator to next element
        next($arr);
    }
}
fclose($f);
print_r($result);

你能提供你的STDIN吗?
3 1 2 3 4 5 6 7 8 9
我看到它是一个
mxn
数组,它们是
rowsxcols
。他们修好了吗?如果是,m和n的值是什么?m=3和n=3的值1 2 3 5 6 7 8 9您需要将资源作为第一个参数
fscanf($handle,'%d',$m)
$:/var/www/html/dummy# php index.php
3 3 1 2 3 4 5 6 7 8 9
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9

        )

)