【问题标题】:Is there a better way to print out my object in PHP?有没有更好的方法在 PHP 中打印出我的对象?
【发布时间】:2016-09-09 14:27:48
【问题描述】:

这是我现在得到的:

$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;
}

回响:

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

到目前为止,我知道我可以使用 for 循环来切换 while 以使事情变得更短。是否有另一种方法可以打印出看起来比这更好的某些行?

编辑:顺便说一句,如果这意味着什么,我正在使用 Laravel。

编辑2:有没有办法在不知道列名的情况下打印出来?

谢谢!

【问题讨论】:

  • 更漂亮?太模糊了。
  • 尝试:回声“
    ”; print_r($result);
  • 添加 html 标签并设置任何你想要的样式。
  • PHP对象也可以被foreach自然遍历。虽然我怀疑基于这里的数据库上下文,你所拥有的只是一个对象数组,所以肯定不需要 json_encode/decode 步骤,foreach 是更好的构造。
  • 请考虑阅读this answer on how the foreach construct works 作为您Edit 2的参考。

标签: php laravel


【解决方案1】:

使用foreach() 进行迭代和使用printf() 回显值会更短。您也可以使用sprintf() 将字符串存储到变量中。

$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']);
}

【讨论】:

    猜你喜欢
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多