douduo2407 2012-02-22 18:15
浏览 55
已采纳

访问嵌套对象数组

Hey guys I can't seem to get the syntax here right, I'm just trying to see if type exists, I've tried

if($obj->type)    /* do something */
if($obj[0]->type) /* do something */
if($obj->type[0]) /* do something */

On this

stdClass::__set_state(
array(
   '0' => 
  stdClass::__set_state(
  array(
     'report_number' => '555',
     'type' => 'citrus',
     'region' => 'Seattle',
     'customer_number' => '9757',
     'customer' => 'The Name',
     'location' => 'West Seattle, WA',
     'shipper' => 'Yamato Transport',
     'po' => '33215',
     'commodity' => 'RARE',
     'label' => 'PRODUCE',
  )),
))

But just can't seem to get it right, I believe it has something to do with [0] being an int instead of varchar but I have no idea....

  • 写回答

2条回答 默认 最新

  • dpdfh60088 2012-02-22 18:28
    关注

    The output in your question is created by var_export which represents the data of the object as an array. But don't get mislead by that, it's in fact an object.

    Object properties are accessed by this syntax:

    $obj->property
    

    In your case the property is named 0 which is hard for PHP to deal with in plain code as it's not a property name you could write right away like this:

    $obj->0
    

    Instead, you need to tell the PHP parser what the name is by enclosing it into {}:

    $obj->{0}
    

    You can then traverse further on to access the type property of 0:

    $obj->{0}->type
    

    Hope this is helpful, the question comes up from time to time, this is a related one with more related links: How do I access this object property?.

    The PHP Manual has this documented, but not very obvious on the Variable variables entry:

    In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置