php - 从 stdClass 对象中提取值

标签 php arrays object

变量 $results 上的我的 var_dump 显示类似这样的内容

array (size=11)
  0 => 
    object(stdClass)[69]
      public 'Tables_in_database-name-here' => string 'wp_commentmeta' (length=14)
  1 => 
    object(stdClass)[68]
      public 'Tables_in_database-name-here' => string 'wp_comments' (length=11)
  2 => 
    object(stdClass)[67]
      public 'Tables_in_database-name-here' => string 'wp_links' (length=8)

  ...

  10 => 
    object(stdClass)[59]
      public 'Tables_in_database-name-here' => string 'wp_users' (length=8)

我希望能够从上述结构中提取表名,并以逗号分隔的形式列出它们,如下所示;

 `wp_commentmeta,wp_comments,wp_links....,wp_users`

不过,我的大脑突然僵住了,不知道如何从该结构中提取这些数据。

我尝试了很多选项,你可以通过下面的代码来遵循它 - 每个选项都会以错误结束!

    foreach ($results as $current_item):
        /*
         * $current_item is something like this:
         * 
         * object(stdClass)[69]
            public 'Tables_in_database-name-here' => string 'wp_commentmeta' (length=14)
         */

        # echo $current_item;      
        # fires an error as "Catchable fatal error: Object of class stdClass could not be converted to string"

        # echo $current_item[1]; 
        # fires an error as "Cannot use object of type stdClass as array in..."

        # echo array_values($current_item); 
        # fires an error as "array_values() expects parameter 1 to be array, object given in .."

        # echo $current_item['Tables_in_database-name-here']; 
        #fires an error as "Cannot use object of type stdClass as array in "

        how do you get that darn thing? :)

    endforeach; 

最佳答案

您的主要问题是属性名称 Tables_in_database-name-here 无法通过通常的 $obj->propertyName 方式表示。 PHP 允许您通过 $obj->{'invalid-variable-name-but-ok-as-a-property'} 使用字符串属性名称。

我只需通过 implode()array_map() 构造字符串,例如

$string = implode(',', array_map(function($result) {
    return $result->{'Tables_in_database-name-here'};
}, $results));

演示 ~ https://eval.in/172247

关于属性名称,您还可以将 stdclass 对象强制转换为数组。例如...

$associativeArray = (array) $result;
// array(1) { ["Tables_in_database-name-here"] => string(14) "wp_commentmeta" }

$indexedArray = array_values($associativeArray);
// array(1) { [0] => string(14) "wp_commentmeta" }

关于php - 从 stdClass 对象中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728284/

相关文章:

php - 在 ubuntu 上使用 VS Code 进行 Xdebug 无法正常工作

php - 如何在选项中输入姓名并发布?

php - 检查网站是否在 iframe 内

ios - 如何将 [String] 拆分成行?

c - C 编译器是否可以随意重写数组中的相邻值?

java - 通过他的属性获取一个元素

javascript类可访问性变量作用域问题

php - cloudflare 的 SSL 错误

java - 单击时更改 JButton ImageIcon

java - Java 中的抽象类 - 创建方法