duan4369 2010-03-30 05:10
浏览 26
已采纳

是否有更短的方法来访问数组中的属性?

$jj_post is the array output debug via print_r(). This variable is an array of objects:

Array
(
    [0] => stdClass Object
        (
            [ID] => 2571
        )

)

I access the object property, ID, via code like this:

$jj_post_id = $jj_post[0]; 
$jj_ID = $jj_post_id->ID;

So, is there a shorter way, cause this is the only thing I know and I feel the code little bit too long?

  • 写回答

2条回答 默认 最新

  • dougou8552 2010-03-30 05:29
    关注

    Well if you are sure $jj_post is always going to be an array, and that it will always contain an stdClass object, then you should access like so:

    $jj_ID = $jj_post[0]->ID;
    

    But it is not always so sometimes. You may not always know the contents of a variable so you need to do some checking to verify that you access areas that are safe and available.

    How long the code is shouldn't be an issue if it performs the job well.

    In my opinion, you have two alternatives:

     $jj_ID = @$jj_post[0]->ID;
    

    This ensures that the runtime errors are silently handled, and not thrown to the standard output.

    Another way would be to check absolutely for presence of each type:

    $jj_ID = "";
    if(is_array($jj_post))
    {
      $jj_post_id = $jj_post[0]; 
      if(!empty($jj_post_id))
      {
        $jj_ID = $jj_post_id->ID;
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计