且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 错误:无法使用 stdClass 类型的对象作为数组(数组和对象问题)

更新时间:2023-10-30 14:43:58

您复制的示例是使用包含数组的数组形式的数据,您使用的是包含对象的数组形式的数据.对象和数组并不相同,因此它们使用不同的语法来访问数据.

The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

如果您不知道变量名称,只需在循环中执行 var_dump($blog); 即可查看它们.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

最简单的方法——直接以对象的形式访问$blog:

尝试(假设这些变量是正确的):

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

另一种方法 - 作为数组访问 $blog:

或者,您可以使用 get_object_vars (文档):

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

值得一提的是,这不一定适用于嵌套对象,因此其可行性完全取决于您的 $blog 对象的结构.

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

优于以上任何一种 - 内联 PHP 语法

说了这么多,如果你想以最易读的方式使用 PHP,以上两种方法都不对.当 PHP 与 HTML 混合使用时,许多人认为使用 PHP 的替代语法是***实践,这会将您的整个代码从九行减少到四行:

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

希望这有帮助.