从stdClass对象中提取值

时间:2014-07-14 00:58:24

标签: php arrays object

变量var_dump上的$results显示了类似

的内容
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`

我有一个关于如何从该结构中提取这些数据的大脑冻结时刻。

我尝试了很多选项,因为你可以通过下面的代码关注它 - 每个都以错误结束uo!

    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; 

1 个答案:

答案 0 :(得分:1)

您的主要问题是属性名称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" }