通过 PDO fetchAll (PDO::FETCH_OBJ) 获取从数据库检索的对象的属性



我确实有一个使用PDO获取ALL(PDO::FETCH_OBJ)从DB检索的对象数组。当我var_dump该数组的第一个元素时: var_dump($this->stockList[0]);我得到:

object(stdClass)[5]
public 'userId' => string '3' (length=1)
public 'symbol' => string 'ibm' (length=3)
public 'date' => string '2019-01-03' (length=10)
public 'quantity' => string '5' (length=1)
public 'bought' => string '1' (length=1)
public 'observed' => string '0' (length=1)
public 'dividendRate' => string '6.28' (length=4)
public 'exDividendDate' => string '2018-11-08' (length=10)
public 'forwardDividend' => string '31.400000000000002' (length=18)

我想在这个对象上使用反射来获取它的所有属性:

$r = new ReflectionClass($this->stockList[0]);
$objProperties = $r->getProperties();

我上了适当的课: var_dump($r); 生产: object(ReflectionClass)[16] public 'name' => string 'stdClass' (length=8)

但我无法获取该对象的属性: var_dump($objProperties);给出一个空数组: array (size=0) empty因此,问题是如何获取该对象的属性列表?我的完整代码:

$sql = "query";
$this->stockList = $this->con->query($sql)->fetchAll(PDO::FETCH_OBJ);
var_dump($this->stockList[0]);
$r = new ReflectionClass($this->stockList[0]);
$objProperties = $r->getProperties();
var_dump($r);
var_dump($objProperties);

使用 StdClass 进行反射将不起作用。对ReflectionClass()参数 1 的调用使用实例的::class来确定其属性。由于 StdClass 默认情况下没有属性并且是动态给出的,因此反射找不到任何属性,因为默认情况下它们不存在。

您可以在演示中看到上述内容。但是,为了更简单,这将正常工作:

var_dump(array_keys((array) new Foo('bar'))); # Based on above demo

但是,不要惊慌。你不需要使用反射来做到这一点:PDO::FETCH_ASSOC会给你一个多维数组。可以使用array_keys()来获取参数。然后,稍后,如果您希望将结果用作对象,请将数组转换为对象。

# Fetch Query
$this->stockList = $this->con->query($sql)->fetchAll(PDO::FETCH_ASSOC);
# Get properties which will be, in this case, ['id', 'symbol', 'date', 'quantity', 'bought', 'observed', 'dividendRate', 'exDividentDate', 'forwardDivident']
$properties      = array_keys($this->stockList[0]);
# Revert all back to StdClass instances by casting the array to object
foreach($this->stockList as &$stockItem) {
    $stockItem = (object) $stockItem;
}

交替,正如@Quasimodosclone的评论中所建议的那样。您可以使用get_object_vars()它将返回对象的数组等效项。然后,像以前一样,使用 array_keys() 获取属性。

$this->stockList = $this->con->query($sql)->fetchAll(PDO::FETCH_OBJ);
$properties      = array_keys(get_object_vars($this->stockList[0]));

出于好奇对此进行测试后,可以将对象强制转换为数组以实现更简单。

$this->stockList = $this->con->query($sql)->fetchAll(PDO::FETCH_OBJ);
$properties      = array_keys( (array) $this->stockList[0] );

最新更新