简体   繁体   中英

Is there a better way to print out my object in PHP?

Here's what I got right now:

$results = DB::select('select * from test_table');
$result= json_decode(json_encode($results), true);

$x=0;
try {
    while ($x<10)
    {
        echo $result[$x]['column_A'];
        echo " ";
        echo $result[$x]['column_B'];
        echo "<br>";
        $x++;
    }
}
catch(exception $e) {
    echo $e;
}

which echos out:

179368 3A
176733 3B
686733 3C
178673 3D
168663 3E
937338 3F
936888 58
186335 59
199366 5A
159373 5B

So far I know that I could switch out while with a for loop to make things slightly shorter. Is there another method of printing out certain rows that looks better than this?

EDIT: By the way, I'm using Laravel if that means anything.

EDIT 2: So is there a way I could print this out without knowing the names of the columns?

Thanks!

Shorter would be with the use of foreach() for iterating and printf() for echo'ing the values. You can also use sprintf() to store the string into a variable.

$results = DB::select('select * from test_table');
$result= json_decode(json_encode($results), true);

foreach ($result as $row) {
    printf('%s %s<br/>', $row['column_A'], $row['column_B']);
}

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