简体   繁体   中英

How to correct print 2D array

I created a two-dimensional array

class MyArray
{
    public $arr=array();

    public function create()
    {
        for($i=0;$i<=4;$i++)
        {
            for($j=0;$j<=4;$j++)
            {
                $this->arr[$i][$j]=0;
            }
        }
    }

    public function print()
    {
        for($i=0;$i<5;$i++)
        {
            for($j=0;$j<5;$j++)
            {
                echo $this->arr[$i][$j] . " ";
            }
        }
    }
}

$arr1= new MyArray();
$arr1->create();
$arr1->print();

but when I display it looks like this:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

What to do to look like this:

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

Just add a <br /> tag after the inner for loop, like this:

public function print(){
    for($i=0;$i<5;$i++){
        for($j=0;$j<5;$j++){
            echo $this->arr[$i][$j] . " ";
        }
        echo "<br />";
    }
}

由于我不知道您是否正在制作网页,因此您将需要echo / print换行符\\n或HTML换行符( <br><br /> )作为MyArray::print外循环的第二条语句MyArray::print ,具体取决于上下文(HTML5或HTML 4.01 / XHTML 1.0)。

This is print in single line because you are not using line break.
You need to add <br> in another for loop as following:

public function print(){
 for($i=0;$i<5;$i++){
    for($j=0;$j<5;$j++){
        echo $this->arr[$i][$j] . " ";
    }
    echo "<br />";
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM