-2

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!

John
  • 326
  • 4
  • 21
  • 4
    Prettier? Too vague. – Jonnix Sep 09 '16 at 14:28
  • 1
    try: echo "
    "; print_r($result);
    – Ish Sep 09 '16 at 14:30
  • 1
    Add html tags and style it whatever way you want. – jeroen Sep 09 '16 at 14:30
  • @JonStirling, updated. Is it still too vague? – John Sep 09 '16 at 14:32
  • 1
    PHP objects can also be traversed naturally by [`foreach`](http://php.net/foreach). Though I suspect based on the DB context here what you have is just an array of objects so there's certainly no need for the json_encode/decode step there and `foreach` is the better construct. – Sherif Sep 09 '16 at 14:32
  • 1
    Please consider reading [this answer on how the `foreach` construct works](http://stackoverflow.com/a/14854568/1878262) as reference to your *Edit 2*. – Sherif Sep 09 '16 at 14:36

1 Answers1

-2

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']);
}
Philipp Palmtag
  • 1,310
  • 2
  • 16
  • 18