【问题标题】:how can I access the value of a stdclass in php如何在 php 中访问 stdclass 的值
【发布时间】:2015-06-18 09:37:06
【问题描述】:

我想访问下图中的int20和int30。我该怎么做?

这是我的 var_dump 结果:

array (size=2)
  0 => 
    array (size=1)
      0 => 
        object(stdClass)[238]
          public 'time' => int 20
  1 => 
    array (size=1)
      0 => 
        object(stdClass)[242]
          public 'time' => int 30

这是我的查询:

$sum_time = array();
foreach ($a as $f) {
    $sum_time[] = DB::select("select time from quiz where '$f'=id");
}        
var_dump($sum_time);

【问题讨论】:

  • 在 stdclass 上使用 -> 例如你的例子中的时间 $theObject->time

标签: php arrays stdclass


【解决方案1】:

虽然这是一个老问题,但它看起来像一个典型的XY problem

如果我们假设问题是我如何检索time 属性?,答案是:

对于数组,您使用[] 运算符:

$arr = array(
    'time' => 20
);

var_dump($arr['time']);
/* 
will return:
  int(20)
*/

对于对象,您使用-> 运算符:

// Can be achieved aso with "new stdClass()";
$myObj = (object) array(
    'time' => 20
);

var_dump($myObj);
/*
Will return:
  object(stdClass)#3 (1) {
    ["time"]=>
    int(20)
  }
*/

var_dump($myObj->time);
/* 
will return:
  int(20)
*/

无论如何,对于未来的情况,重要的是要提供一些背景,可能真正问题的解决方案甚至不包括这个问题......

【讨论】:

    【解决方案2】:
        $sum_time = array();
        $time = array();
        $count=0;
        foreach ($a as $f) {
            $sum_time[] = DB::select("select time from quiz where '$f'=id");
            $time[]=$sum_time[$count]->time;
            $count++;
        }   
    print_r($time)     
        var_dump($sum_time);
    

    【讨论】:

      【解决方案3】:

      您可以将->object 用于stdClass。 例如。

      $v = new StdClass();
      $v->name = "Mohsen";
      $v->addr = "somewhere";
      
      $tmp = array("data" => "other data","detail" => $v);
      var_dump($tmp);
      
      echo "<br /><br />";
      echo $tmp["detail"]->name; // Access your stdClass object
      

      【讨论】:

        【解决方案4】:

        将此添加到您的代码中以获得所有“时间”值的数组

        $times = array();
        foreach ($sum_time as $value) {
            $times[] = $value[0]->time;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-22
          • 1970-01-01
          • 1970-01-01
          • 2014-09-24
          • 2016-11-12
          • 2014-10-17
          • 1970-01-01
          • 2011-06-07
          相关资源
          最近更新 更多