【问题标题】:Why is the data only displaying when it's in a foreach loop but outside it's a non-object?为什么数据仅在 foreach 循环中但在非对象之外时才显示?
【发布时间】:2012-09-19 01:39:12
【问题描述】:

我是 PHP 新手,对此有点困惑..

当我有这个时,它会显示数据

<?php foreach ($profile as $p):?>
    <?php echo $profile->custom_url;?>
                    <?php endforeach?>

但是当我这样做时,我得到“尝试获取非对象的属性”

   <?php echo $profile->custom_url;?>

然而,我已经看到它不在 foreach 循环中的代码并且数据显示。谁能帮忙解释一下这是为什么?

【问题讨论】:

    标签: php mysql arrays codeigniter


    【解决方案1】:

    您的 foreach 应具有 (array_expression as $value) 的格式。 source

    <?php foreach ($profile as $p):?>
    <?php echo $p->custom_url;?>
    <?php endforeach?>
    

    【讨论】:

    • 好的,但是为什么 custom_url;?> 不能在 foreach 之外工作?
    • 什么是 $profile?数组?做一个 var_dump($profile) 并在此处发布。显然它不是一个对象,PHP 告诉你。如果 $profile 是对象数组,则 foreach 将起作用。
    • 它是一个数组。这是否意味着每次我看到类似 echo $profile->custom_url 的东西时,它是如何转换为对象的?
    • 你可以简单地通过 (object)$profile 将数组转换为对象
    【解决方案2】:
    // $profile is an array
    <?php foreach ($profile as $profile):?>
        // inside foreach $profile is the element of the array $profile
        <?php echo $profile->custom_url;?>
    <?php endforeach?>
    
    // $profile is an array not an object
    <?php echo $profile->custom_url;?>
    
    // You'd better use another variable name for the element.
    <?php foreach ($profile as $element):?>
        <?php echo $element->custom_url;?>
    <?php endforeach?>
    

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 1970-01-01
      • 2018-10-17
      • 2016-06-24
      • 2012-12-22
      • 1970-01-01
      • 2011-12-20
      • 2014-03-26
      • 2017-04-02
      相关资源
      最近更新 更多