如何从数组中的stdClass对象访问变量


How do I access a variable from an stdClass object within an Array of Arrays?

我在数组$total上执行了print_r,它返回以下内容:

Array ( ) Array ( ) Array ( ) Array ( ) Array ( [0] => stdClass Object ( 
[generated] => 6 [magnitude] => 3 [log_pk] => 14 [result] => 0.5000 ) )
Array ( ) Array ( )

我需要能够从stdClass Object中打印出log_pk。我试过print $total[0]->log_pk,但没有成功。错误为Undefined offset: 0。感谢您的帮助。谢谢

所以这是在一个循环中,您应该首先检查索引0是否存在。

if (isset($total[0])) echo $total[0]->log_pk

您是否在循环中执行此操作?如果是这样,那么在大多数迭代中,数组看起来都是空的。尝试:

if (!empty($total)) print $total[0]->log_pk;

var_dump()显示有关一个或多个表达式的结构化信息,其中包括其类型和值。数组和对象以递归方式探索,值缩进以显示结构。

var_dump($total)

PHP:var_dump-手动

看起来您的print_r在一个循环中。

while(true){
    $total = some_function();
    print_r($total);
    if($condition) break;
}
// Here - outside the loop, is not the right place for the print_r();

如果您想在循环外打印,您可以将$total = some_function();更改为$total[] = some_function();,然后您可以执行print_r($total[index])