【问题标题】:Getting data from an array?从数组中获取数据?
【发布时间】:2011-05-23 03:40:18
【问题描述】:

我的 var_dump($gallery) 看起来像这样:

array(1) 
        { [0]=> object(stdClass)#102 (9) { 
            ["term_id"]=> string(2) "17" 
            ["name"]=> string(5) "Image" 
            ["slug"]=> string(5) "image" 
            ["term_group"]=> string(1) "0" 
            ["term_taxonomy_id"]=> string(2) "19" 
            ["taxonomy"]=> string(18) "gallery" 
            ["description"]=> string(0) "" 
            ["parent"]=> string 
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus et               tempus tellus. Integer euismod, est et ultricies tristique, urna ipsum              semper elit, pharetra cursus ligula turpis sed libero. Vestibulum ante              ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;             Suspendisse pellentesque orci sed tellus hendrerit a auctor augue               commodo. Ut nibh lacus, …
            Read more... 
            (1) "0" 
            ["count"]=> string(1) "1" 
            } 
        }

而且我无法从内部获取数据(在这种情况下,我想回显“图像”)。例如:

$gallery[] 输出

致命错误:无法使用 [] 读取 [源文件 url]

$gallery[0] 节目

可捕获的致命错误:stdClass 类的对象无法在 [源文件 url] 中转换为字符串

$gallery[1]、$gallery[2] 等等都是空的。

据我所知,PHP $gallery[0][3] 应该可以完成这项工作,但是如果我无法回显 stdClass 对象,该怎么办? :/ $gallery[0]['slug'] 顺便说一句也有效吗?

非常感谢。

是的 - 我无法更改数组中的第一项,它是由 Wordpress 生成的,但我在这里问是因为这是严格的 PHP 问题。

干杯。

【问题讨论】:

    标签: php arrays multidimensional-array stdclass


    【解决方案1】:

    像这样的全遍历:

    foreach ($gallery as $key=>$value)
    {
      print $key;
      print $value;
    }
    

    希望对您有所帮助 :) 在内部,您可以获取第一个 $key 作为对象并像 $key->image 一样进行操作

    【讨论】:

    • 必须为-1,这是错误的。这将导致他在尝试打印$gallery[0] 时遇到的相同错误。问题是他正在将一个对象转换为一个字符串,这正是你想要做的。
    【解决方案2】:

    $gallery 是一个数组,包含一个 StdClass 类型的对象。

    您想访问索引 0 处保存的对象的 slug 成员:

    $gallery[0]->slug;
    

    【讨论】:

    • 谢谢我的主人! $gallery[0][slug] 和 #gallery[0]->slug 有什么区别?
    • [] 用于数组索引,-> 用于访问方法/对象的成员。 $gallery[0] 是一个对象,所以使用->
    • slug 是一个对象属性,如果 $gallery[0][slug] 这不起作用,您需要将其用作属性。 $gallery[0]['slug'] 将是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多